Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
23 views90 pages

E-Record 2240449

Uploaded by

kayomain214
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views90 pages

E-Record 2240449

Uploaded by

kayomain214
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Python Programming for Mathematical Modelling

MAT451

PYTHON E - Record

Sreshta P

2240449
INDEX

Topic Page No

LAB 1-Recapitulation of Python commands and 1-7


programming structure

LAB 2-Plot 2D and 3D, Graph Customization. 8-23

LAB 3-Solving calculus problems: functions, 24-40


limits, continuity using python

LAB 4-Solving calculus problems: derivatives, 41-46


cost function, revenue using python

LAB 5-Application of derivatives: marginal cost, 46-47


marginal revenue

LAB 6-Differential equations in sympy 48-53

LAB 7-Construction of slope fields of an 53-68


ordinary differential equation and plotting
solution curves

LAB 8 -Mathematical Model: Interest Rates 69-73

LAB 9 -Mathematical Model: Growth of a 73-75


population – Exponential Model

LAB 10-Mathematical Model: Logistic Growth. 75-81

LAB 11 -Mathematical Model: Simple pendulum 82-85

LAB 12 -Mathematical Model: Spreading of 86-88


diseases
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

LAB 2-Plot

2D Plott
In [2]: import numpy as np
import matplotlib.pyplot as plt

In [3]: # Write a python program to grt graph of exponential function


x=np.linspace(1,20,100)
y=np.exp(x)
plt.plot(x,y)
plt.show()

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 1 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [3]: x = np.linspace(0, 2, 50)


y1 = x
y2, y3 = [], []
[y2.append(i**2) for i in x]
[y3.append(i**3) for i in x]
plt.grid()
plt.axis((0, 2, 0, 2))
plt.title("Powers of x")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.plot(x, y1, 'r--', markersize=1, linewidth=1.2)
plt.plot(x, y2, 'bs', markersize=4, linewidth=2.2)
plt.plot(x, y3, 'g^', markersize=12, linewidth=3.2)
plt.legend(["f(x)=x", "g(x)=x^2", "h(x)=x^3"], loc="upper left")
plt.show()

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 2 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [4]:
# Write a python program plotting graphs of the three functions of your ch

x=np.linspace(1,50,50)
y=np.linspace(1,20,100)
z=np.linspace(1,30,100)
a=x
b=y**2
c=z*10
plt.plot(x,a,lw=5,ls='--')
plt.plot(y,b,lw=3,ls='dotted')
plt.plot(z,c,lw=10,ls='dashdot')
plt.title("2240442")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.grid()
plt.legend(['blue','green','orange'])
plt.show()

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 3 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [4]: t = np.linspace(-100, 100, 1000)


plt.plot(t, 16*np.sin(t)/t, ls='-', lw=1.2, label="f(x)=16sin(x)/x", co
plt.grid()
plt.title("functions")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend(loc="upper left")
plt.plot(t, t/np.log(t), lw=2.3, label="f(x)=x/lnx", color="#698707", l
plt.show()

/var/folders/c7/zvy4yqhd2ll5fkss8sx4sfbc0000gn/T/ipykernel_3564/49
3276448.py:8: RuntimeWarning: invalid value encountered in log
plt.plot(t, t/np.log(t), lw=2.3, label="f(x)=x/lnx", color="#698
707", ls=":")

f(x)=16sin(x)/x

www..orm

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 4 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [7]: # Consider the average heights and weights of persons stored in the lis
#height =[121.9,124.5,129.5,134.6,139.7,147.3,152.4,157.5,162.6]
#weight =[19.7,21.3,23.5,25.9,28.5,32.1,35.7,39.6,43.2]

height=[121.9,124.5,129.5,134.6,139.7,147.3,152.4,157.5,162.6]
weight=[19.7,21.3,23.5,25.9,28.5,32.1,35.7,39.6,43.2]
plt.grid()
plt.plot(height,weight,markersize=10,color='g',marker='*',linestyle='--
plt.title("Average weight with respect to average heigt")
plt.xlabel("Weight in Kgs")
plt.ylabel("Height in cm")
plt.show()

2D and 3D, Graph Customization.


In [5]: from numpy import *
from matplotlib.pyplot import*
from mpl_toolkits import mplot3d
plt.figure(figsize=(6, 6))
x = np.linspace(-2, 2, 100)
plt.subplot(3, 2, 1)
y = x
plt.plot(x, y, color="blue")
plt.xlabel('$x$')
plt.ylabel('$x$')
plt.subplot(3, 2, 2)
y = x**2
plt.plot(x, y, color="green")
plt.xlabel('$x$')
plt.ylabel('$x^2$')
plt.subplot(3, 2, 3)
y = x**3
plt.plot(x, y, color="red")
plt.xlabel('$x$')

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 5 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

plt.ylabel('$x^3$')
plt.subplot(3, 2, 4)
y = x**4
plt.plot(x, y, color="black")
plt.xlabel('$x$')
plt.ylabel('$x^4$')
plt.subplot(3, 2, 5)
y = x**5
plt.plot(x, y, color="yellow")
plt.xlabel('$x$')
plt.ylabel('$x^5$')
plt.subplot(3, 2, 6)
y = x**6
plt.plot(x, y, color="pink")
plt.xlabel('$x$')
plt.ylabel('$x^6$')
plt.suptitle('Ploynomial Functions')
plt.tight_layout()
plt.subplots_adjust(top=0.90)

Three Dimensional Plot

1. Line Plots: Function is given in prarametric form

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 6 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [6]: ax = plt.axes(projection='3d')

0.0
0.2
da
0.6

In [7]: ax = plt.axes(projection='3d')
z = np.linspace(0, 15, 100)
x = np.sin(z)
y = np.cos(z)
ax.plot3D(x, y, z)
plt.show()

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 7 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [9]: ax = plt.axes(projection='3d')
t = np.linspace(0, 1, 10)
x = 7*t - 2
y = 8 + 2*t
z = 3*t - 5
ax.plot3D(x, y, z, '#15cfa3')
plt.title("A 3D Plot")
ax.set_xlabel("X")
ax.set_xlabel("Y", size=16, color='#4769a1')
ax.set_xlabel("Z", fontsize=12)
Text(0.5, 0, 'Z')

Out[9]: Text(0.5, 0, 'Z')

2. Scatter Plot

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 8 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [10]: ax = plt.axes(projection='3d')
# data for 3 dimensional line
z = np.linspace(0, 100, 1000)
x = np.sin(z)
y = np.cos(z)
ax.scatter3D(x, y, z)
plt.show()

0.0

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 9 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [11]: x = np.random.random(150)
y = np.random.random(150)
z = np.random.random(150)
fig = figure(figsize=(12, 12))
ax = axes(projection='3d')
ax.grid()
ax.scatter(x, y, z, color="#e8c425")
ax.set_title('3D Scatter Plot')
ax.set_xlabel("X")
ax.set_xlabel("Y")
ax.set_xlabel("Z")

Out[11]: Text(0.5, 0, 'Z')

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 10 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [12]: xx, zz = np.meshgrid(range(10), range(10))


y = 0
# plot the surface
ax = axes(projection='3d')
ax.plot_surface(xx, y, zz, color="#d1f79c")
title("Plane")
ax.set_xlabel("X")
ax.set_xlabel("Y")
ax.set_xlabel("Z")

Out[12]: Text(0.5, 0, 'Z')

0.04
0.02
0.00
-007

04

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 11 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [13]: xx, yy = np.meshgrid(range(10), range(10))


z = 0
# plot the surface
ax = plt.axes(projection='3d')
ax.plot_surface(xx, z, yy, color="#ec748d")
plt.title("Plane")
ax.set_xlabel("X")
ax.set_xlabel("Y")
ax.set_xlabel("Z")

Out[13]: Text(0.5, 0, 'Z')

0.04
0.02
0.00
-007

04
In [15]: ax = axes(projection='3d')
u = linspace(0, 2*pi, 100)
v = np.linspace(0, pi, 100)
x = 10*outer(cos(u), sin(v))
y = 10*outer(sin(u), sin(v))
z = 10*outer((ones(size(v))), cos(v))
ax.plot_surface(x, y, z, cmap="Wistia", cstride=9)
show()

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 12 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [16]: ax = axes(projection='3d')
u = linspace(0, 2*pi, 100)
v = np.linspace(0, 8, 100)
x = 10*outer(ones((size(u))), cos(u))
y = 10*outer(ones(size(u)), sin(u))
z = 10*outer(v, (ones(size(v))))
ax.plot_surface(x, y, z, color="#94fc03")
show()

In [17]: ax = axes(projection='3d')
u = linspace(0, 2*pi, 100)
u = linspace(-2, 2, 200)
x = outer(v, cos(u))
y = outer(v, sin(u))
z = outer(v, ones(size(u)))
ax.plot_surface(x, y, z, cmap="PuRd")
show()

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 13 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [18]: ax = axes(projection = '3d')


x = arange(-3*pi, 3*pi, 0.1)
y = arange(-3*pi, 3*pi, 0.1)
xx, yy = meshgrid(x, y)
z = sin(xx)*sin(yy)
ax.plot_surface(xx, yy, z, cmap="magma", cstride=2)
show()

In [19]: ax = axes(projection='3d')
x = arange(-3*pi, 3*pi, 0.1)
y = arange(-3*pi, 3*pi, 0.1)
xx, yy = meshgrid(x, y)
z = (xx) + (yy)
ax.plot_surface(xx, yy, z, cmap=cm.Spectral, cstride=2)
show()

3. Vector feilds

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 14 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

In [20]: x, y = meshgrid(linspace(-5, 5, 10), linspace(-5, 5, 10))


u = x/sqrt(x**2 + y**2)
v = y/sqrt(x**2 + y**2)
quiver(x, y, u, v, color="#e874c0")
show()

In [22]: fig=figure()
ax=axes(projection='3d')
x,y,z=meshgrid(arange(-0.8,1,0.2),
arange(-0.8,1,0.2),
arange(-0.8,1,0.8))
u=sin(pi*x)*cos(pi*y)*cos(pi*z)
v=-cos(pi*x)*sin(pi*y)*cos(pi*z)
w=(sqrt(2.0/3.0)*cos(pi*x)*cos(pi*y)*sin(pi*z))
ax.quiver(x,y,z,u,v,w,length=0.3, color="#ffd700")
show()

-0.5
00

In [ ]:

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 15 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM

http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 16 of 16
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

LAB 3

Trignometric Functions

In [ ]: math.acos()
math.acosh()
math.asin()
math.asinh()
math.atan()
math.atan2()
math.atanh()
math.ceil()
math.comb()
math.cos()
math.cosh()
math.degrees()
math.dist(P, Q)
math.exp()
math.expm1()
math.fabs()
math.factorial()
math.floor()
math.fmod()
math.fsum()
math.gamma()
math.gcd()
math.hypot() # returns eucledian norm
math.isqrt() #floor(sqrt())
math.log()
math.log10()
math.tan()
math.tanh()
math.trunc()

In [2]: from math import *


from sympy import Symbol
from sympy import *
from numpy import linspace, sin, arange
from cmath import *

In [3]: sin(pi/2)

Out[3]: (1+0j)

math.sin() works for numerical values. it gives an error when it uses symbol.

http://localhost:8889/notebooks/LAB%203.ipynb Page 1 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

In [4]: x = Symbol('x')
y = sin(x)
y

------------------------------------------------------------------
---------
TypeError Traceback (most recent c
all last)
Input In [4], in <cell line: 2>()
1 x = Symbol('x')
----> 2 y = sin(x)
3 y

File ~/opt/anaconda3/lib/python3.9/site-packages/sympy/core/expr.p
y:350, in Expr.__complex__(self)
348 result = self.evalf()
349 re, im = result.as_real_imag()
--> 350 return complex(float(re), float(im))

File ~/opt/anaconda3/lib/python3.9/site-packages/sympy/core/expr.p
y:345, in Expr.__float__(self)
343 if result.is_number and result.as_real_imag()[1]:
344 raise TypeError("Cannot convert complex to float")
--> 345 raise TypeError("Cannot convert expression to float")

TypeError: Cannot convert expression to float

In [58]: sin(pi/2)
x = Symbol('x')
y = sin(x)
y

Out[58]: sin (𝑥)

program to check whether the expression x + 5 is greater than 0

In [8]: x = Symbol('x', positive=True)


"""positive=True should be specified else SymPy does not know anything
the isgn of x, it cannot deduce whether x+5>0 so it displays an error.
create an object specifying positive=True, we tell SYmPy to assume only
positive values of x."""
# check the condition
if x+5 > 0:
print("Do Something")
else:
print("Do Something else")

Do Something

http://localhost:8889/notebooks/LAB%203.ipynb Page 2 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

We can use the solve() function to express one variable in an equation in terms of other

In [9]: x, y = symbols(('x', 'y'))


solve(2*x + 3*y - 5, y)

Out[9]: [5/3 - 2*x/3]

Derieve the quadratic forumal for solving the equation 𝑎𝑥2 + 𝑏𝑐 + 𝑐

In [11]: a, b, c, x = symbols(('a', 'b', 'c', 'x'))


solve(a*x**2 + b*x + c, x)

Out[11]: [(-b - sqrt(-4*a*c + b**2))/(2*a), (-b + sqrt(-4*a*c + b**2))/(2*


a)]

solving for the cubic formula

In [12]: a, b, c, d, x = symbols(('a', 'b', 'c', 'd', 'x'))


solve(a*x**3 + b*x**2 + c*x + d, x)

Out[12]: [-(-3*c/a + b**2/a**2)/(3*(sqrt(-4*(-3*c/a + b**2/a**2)**3 + (27*


d/a - 9*b*c/a**2 + 2*b**3/a**3)**2)/2 + 27*d/(2*a) - 9*b*c/(2*a**
2) + b**3/a**3)**(1/3)) - (sqrt(-4*(-3*c/a + b**2/a**2)**3 + (27*
d/a - 9*b*c/a**2 + 2*b**3/a**3)**2)/2 + 27*d/(2*a) - 9*b*c/(2*a**
2) + b**3/a**3)**(1/3)/3 - b/(3*a),
-(-3*c/a + b**2/a**2)/(3*(-1/2 - sqrt(3)*I/2)*(sqrt(-4*(-3*c/a +
b**2/a**2)**3 + (27*d/a - 9*b*c/a**2 + 2*b**3/a**3)**2)/2 + 27*d/(
2*a) - 9*b*c/(2*a**2) + b**3/a**3)**(1/3)) - (-1/2 - sqrt(3)*I/2)*
(sqrt(-4*(-3*c/a + b**2/a**2)**3 + (27*d/a - 9*b*c/a**2 + 2*b**3/
a**3)**2)/2 + 27*d/(2*a) - 9*b*c/(2*a**2) + b**3/a**3)**(1/3)/3 -
b/(3*a),
-(-3*c/a + b**2/a**2)/(3*(-1/2 + sqrt(3)*I/2)*(sqrt(-4*(-3*c/a +
b**2/a**2)**3 + (27*d/a - 9*b*c/a**2 + 2*b**3/a**3)**2)/2 + 27*d/(
2*a) - 9*b*c/(2*a**2) + b**3/a**3)**(1/3)) - (-1/2 + sqrt(3)*I/2)*
(sqrt(-4*(-3*c/a + b**2/a**2)**3 + (27*d/a - 9*b*c/a**2 + 2*b**3/
a**3)**2)/2 + 27*d/(2*a) - 9*b*c/(2*a**2) + b**3/a**3)**(1/3)/3 -
b/(3*a)]

Derieve the fexpression for the time it takes for a body in projectile motion to reach the
highest point if its thrown with initial velocity u at an angle . At the highest point, the
vertical component of a peojectile motion is 0. That is usin(Q) - gt = 0

In [13]: u, t, g, theta = symbols(('u', 't', 'g', 'theta'))


solve(u*sin(theta)-g*t, t)
...

http://localhost:8889/notebooks/LAB%203.ipynb Page 3 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

Derieve the expression for determining hypotenuse of a right angled triangle. Using that
find the hypotenuse of a right angled triangle with given base and altitude.

In [14]: h = Symbol('h', positive=True)


o, a = symbols('o, a')
print(solve(h**2-o**2-a**2, h))
o = float(input("Enter the length of the opposite side."))
a = float(input("Enter the length of the adjacent side."))
solve(h**2-o**2-a**2, h)
h

[-sqrt(a**2 + o**2), sqrt(a**2 + o**2)]


Enter the length of the opposite side.8
Enter the length of the adjacent side.9

Out[14]: ℎ

1
Using the formula for equations of motion S = ut + 2 𝑎𝑡2 , derieve the equation for

. Time (t) . Accleration (a) . Initial velocity (u)

In [15]: S, u, t, a = symbols('S, u, t, a')


exp = u*t + 1/2*a*t**2 - S
print("1. time is given by,", solve(exp, t))
print("1. acceleration is given by,", solve(exp, a))
print("1. initial velocity is given by,", solve(exp, u))

1. time is given by, [(-u - 1.4142135623731*sqrt(S*a + 0.5*u**2))/


a, (-u + 1.4142135623731*sqrt(S*a + 0.5*u**2))/a]
1. acceleration is given by, [2.0*(S - t*u)/t**2]
1. initial velocity is given by, [S/t - 0.5*a*t]

Functions

Python Lambda Function are anon functions, meaning they are functions without a name.

1. This function can have any number of arguements but only one expression, which is
evaluated and returned.
2. lambda functions can be used in wherever function objects are required.
3. lambda functions are syntactically restricted to a single expression

In [16]: # to evaluate value of the function at some point x


f = lambda x : x**2 + 3*x - 8
f(3.14)

Out[16]: 11.279600000000002

http://localhost:8889/notebooks/LAB%203.ipynb Page 4 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

In [17]: # to get f(y) when f(x) is defined


y = Symbol('y')
f = lambda x : x**2 + 3*x - 8
f(y)

Out[17]: 𝑦2 + 3𝑦 − 8

1. f(x) = sinx and g(x) = 𝑥2 +𝑥

In [21]: def f(x):


func_fx = sin(x)
return func_fx
def g(y):
func_gy = y**2+y
return func_gy
print("f(2)=", f(2))
print("g(2)=", g(2))
def add(f, g):
return lambda x : (f(x)+g(x))
comp_comp = add(f, g)
print("f+g(2)=", comp_comp(2))
def sub(f, g):
return lambda x : (f(x)-g(x))
comp_comp = sub(f, g)
print("f-g(2)=", comp_comp(2))
def mult(f, g):
return lambda x : (f(x)*g(x))
comp_comp = mult(f, g)
print("f*g(2)=", comp_comp(2))
def div(f, g):
return lambda x : (f(x)/g(x))
comp_comp = div(f, g)
print("f/g(2)=", comp_comp(2))
def comp(f, g):
return lambda x : (f(g(x)))
comp_comp1 = comp(f, g)
comp_comp2 = comp(g, f)
print("f(g(2))=", comp_comp1(2))
print("g(f(2))=", comp_comp2(2))

f(2)= (0.9092974268256817-0j)
g(2)= 6
f+g(2)= (6.909297426825682+0j)
f-g(2)= (-5.090702573174318-0j)
f*g(2)= (5.45578456095409+0j)
f/g(2)= (0.1515495711376136-0j)
f(g(2))= (-0.27941549819892586+0j)
g(f(2))= (1.7361192372574878+0j)

http://localhost:8889/notebooks/LAB%203.ipynb Page 5 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

2. f(x) = 3x and g(x) = 2x + 5 verify that f(g(x)) ≠ g((f(x)) at all points

In [68]: def f(x):


func_fx = 3*x
return func_fx

def g(y):
func_gy = 2*y+5
return func_gy

def comp(a, b):


return lambda x : (a(b(x)))

http://localhost:8889/notebooks/LAB%203.ipynb Page 6 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

In [89]: comp_copm1=comp(f,g)
comp_comp2=comp(g,f)
x=Symbol('x')
print("f(x)=",f(x),"\ng(x)=",g(x),sep="")
x=linspace(-50,50,20)
y1=[]
y2=[]
[y1.append(comp_comp1(i)) for i in x]
[y2.append(comp_comp2(i)) for i in x]
c=0
for i in range(20):
if y1[i]!=y2[i]:
print("f(g({x})) = {y1}, and g((f({x})) = {y2}".format(x=i, y1=
if c>0:
print("\nHence, f(g(x))≠g((f(x)) at all points.")

f(x)=3*x
g(x)=2*x + 5
f(g(0)) = -0.43, and g((f(0)) = -295.0
f(g(1)) = 0.53, and g((f(1)) = -263.42
f(g(2)) = -0.97, and g((f(2)) = -231.84
f(g(3)) = -0.89, and g((f(3)) = -200.26
f(g(4)) = -1.00000000000000, and g((f(4)) = -168.68
f(g(5)) = -0.05, and g((f(5)) = -137.11
f(g(6)) = 0.45, and g((f(6)) = -105.53
f(g(7)) = 0.25, and g((f(7)) = -73.95
f(g(8)) = -0.85, and g((f(8)) = -42.37
f(g(9)) = -0.91, and g((f(9)) = -10.79
f(g(10)) = -0.13, and g((f(10)) = 20.79
f(g(11)) = 0.89, and g((f(11)) = 52.37
f(g(12)) = -0.80, and g((f(12)) = 83.95
f(g(13)) = -0.38, and g((f(13)) = 115.53
f(g(14)) = 0.29, and g((f(14)) = 147.11
f(g(15)) = -0.18, and g((f(15)) = 178.68
f(g(16)) = -0.97, and g((f(16)) = 210.26
f(g(17)) = 0.99, and g((f(17)) = 241.84
f(g(18)) = -0.81, and g((f(18)) = 273.42
f(g(19)) = -0.83, and g((f(19)) = 305.0

To read function from user

http://localhost:8889/notebooks/LAB%203.ipynb Page 7 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

In [90]: x = Symbol('x')
a = input("Enter the first function in terms of x: ") # reading functio
f = lambda x: eval(a)
# f will be stored as an anon function of x using the variable x
f(x)
# lambda function calling using another variable because lambda itself
# return the variable without the value

Enter the first function in terms of x: x**2+exp(x)-18

Out[90]: 𝑥2 + 𝑒𝑥 − 18

Write a program to read functions from user and evaluate its

1. sum
2. difference
3. product
4. quotient
5. composition

In [31]: x, y = symbols('x, y')


fx = eval(input("Enter the first function in terms of x: "))
gx = eval(input("Enter the first function in terms of x: "))
f = lambda x: fx
g = lambda y: gx
print("f + g = ", f(x)+g(x))
print("f - g = ", f(x)-g(x))
print("f * g = ", f(x)*g(x))
print("f / g = ", f(x)/g(x))
print("fog = ", f(g(x)))
print("gof = ", g(f(x)))

Enter the first function in terms of x: x**2 - 3


Enter the first function in terms of x: 3*x**2 - x + 6
f + g = 4*x**2 - x + 3
f - g = -2*x**2 + x - 9
f * g = (x**2 - 3)*(3*x**2 - x + 6)
f / g = (x**2 - 3)/(3*x**2 - x + 6)
fog = x**2 - 3
gof = 3*x**2 - x + 6

In [91]: x = Symbol('x')
m = Limit(1/x, x, S.Infinity)
m

Out[91]: 1
lim
𝑥→∞ 𝑥

http://localhost:8889/notebooks/LAB%203.ipynb Page 8 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

In [92]: # To find the value of the limit we use the .doit() function
m.doit()

Out[92]: 0

The prominent mathematician James Bernoulli discovered that as the value of increases,
the term (1 + 1𝑛 ) 𝑛 approaches the value of e- the constant that we can verify by finding
the limit of the function:

In [93]: n = Symbol('n')
e = Limit((1+1/n)**n, n, S.Infinity).doit()
e

Out[93]: 𝑒

In [35]: # SymPy is a module for symbolic mathematics


x, y, z = symbols('x, y, z')

Find limx→2 𝑥2 + 2

In [36]: limit(x**2+2, x, 2)

Out[36]: 6

Find limx→1(𝑥2 + 2)

In [37]: limit(x**2+2, x, 1)

Out[37]: 3

To dtermine the value from LHL and RHL

1. f(x) = 𝑥2 + 2𝑥 + 1

http://localhost:8889/notebooks/LAB%203.ipynb Page 9 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

In [39]: def limit():


n = float(input("enter the value of limit point: "))
print("z tends to n from LHS")
l = linspace(n-0.1, n, 10)
f1 = l**2+2*l+1
print(f1)
print("z tends to n from right hand side")
m = linspace(n, n+0.1, 10)
f2 = m**2+2*m+1
print(f2[::-1])
print("z at n")
f3 = n**2+2*n+1
print(f3)
limit()

enter the value of limit point: 5


z tends to n from LHS
[34.81 34.94123457 35.07271605 35.20444444 35.33641975 35.46
864198
35.60111111 35.73382716 35.86679012 36. ]
z tends to n from right hand side
[37.21 37.0745679 36.93938272 36.80444444 36.66975309 36.53
530864
36.40111111 36.26716049 36.13345679 36. ]
z at n
36.0

In [40]: def limit():


n = float(input("enter the value of limit point: "))
print("z tends to n from LHS")
l = arange(n-0.1, n, 1)
f1 = sin(1/l)/(1/l)
print(f1)
print("z tends to n from right hand side")
m = linspace(n, n+0.1, 1)
f2 = sin(1/m)/(1/m)
print(f2[::-1])
print("z at n")
f3 = sin(1/n)/(1/n)
print(f3)
limit()

enter the value of limit point: 3


z tends to n from LHS
[0.98029981+0.j]
z tends to n from right hand side
[0.98158409+0.j]
z at n
(0.9815840903884566+0j)

http://localhost:8889/notebooks/LAB%203.ipynb Page 10 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

In [41]: # Finding the right hand limit


x = Symbol('x')
rlim = Limit(1/x, x, 0, dir='+').doit()
rlim

Out[41]: ∞

In [42]: # Finding the left hand limit


x = Symbol('x')
llim = Limit(1/x, x, 0, dir='-').doit()
llim

Out[42]: −∞

find if the limit exists :

f(x) = sin(x) at x=0


f(x) = -5 at x=0
f(x) = 2x + 1 at x=0
f(x) =$\frac{5x}{3} +7 at x=0$

In [43]: import sympy as sp


from sympy import sin
x = Symbol('x')
f = sin(x)
value = 0
def checklim(func, x, symbol):
return sp.limit(func, symbol, x).is_real
print(checklim(f, value, x))

True

In [44]: x = Symbol('x')
f = x - 5
value = 2
def checklim(func, x, symbol):
return sp.limit(func, symbol, x).is_real
print(checklim(f, value, x))

True

In [45]: def checklim(func, x, symbol):


return sp.limit(func, symbol, x).is_real
print(checklim(f, value, x))

True

Find the continuity of the following functions

http://localhost:8889/notebooks/LAB%203.ipynb Page 11 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

𝑥 2 −4
f(x) = 𝑥−2 𝑎𝑡𝑥 = 2

In [47]: def checkcont(f, var, c):


f = simplify(f)
rlim = Limit(f, var, c, dir='+').doit()
llim = Limit(f, var, c, dir='+').doit()
value = f.subs({var:c})
if rlim == llim == value:
return "Function is continuous"
else:
return "Function is discontinuous"

In [48]: from sympy import sin


x = Symbol('x')
f = (x - 2)*(x + 2)/ (x - 2)
g = sin(x)
h = x - 5
i = 2*x + 7
j = 5*x/7 + 3
k = sin(x)/x
print(checkcont(f, x, 2))
print(checkcont(g, x, 0))
print(checkcont(h, x, 2))
print(checkcont(i, x, 0))
print(checkcont(j, x, 3))
print(checkcont(k, x, 0))

Function is continuous
Function is continuous
Function is continuous
Function is continuous
Function is continuous
Function is discontinuous

Continuity:

Find the continuity of the following functions

𝑥 2 −4
a. f(x) = 𝑥−2 𝑎𝑡𝑥 = −2

http://localhost:8889/notebooks/LAB%203.ipynb Page 12 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

In [49]: #a
from sympy import Limit, Symbol, S
x = Symbol ('x')
f = (x**2 - 4) / (x - 2)
xt = -2
print(f)
rlim = Limit(f,x,xt,dir='+').doit()
print("RHL : ", rlim)
llim = Limit(f,x,xt,dir='-').doit()
print("LHL : ", llim)
lim = Limit(f,x,xt).doit()
fc = (xt**2 - 4) / (xt - 2)
if llim==rlim and lim==fc:
print("Function is continuous")
else:
print("Function is not continous")
print("\n")

(x**2 - 4)/(x - 2)
RHL : 0
LHL : 0
Function is continuous

b. f(x) = sin x at x = 0

http://localhost:8889/notebooks/LAB%203.ipynb Page 13 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

In [52]: #b
from sympy import Limit, Symbol, S
from sympy import sin
x = Symbol ('x')
f = sin(x)
xt = 0
print(f)
rlim = Limit(f,x,xt,dir='+').doit()
print("RHL : ", rlim)
llim = Limit(f,x,xt,dir='-').doit()
print("LHL : ", llim)
lim = Limit(f,x,xt).doit()
fc = sin(xt)
if llim==rlim and lim==fc:
print("Function is continuous")
else:
print("Function is not continous")
print("\n")

sin(x)
RHL : 0
LHL : 0
Function is continuous

c. f(x) = x - 5 at x = 2

http://localhost:8889/notebooks/LAB%203.ipynb Page 14 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

In [53]: #c
from sympy import Limit, Symbol, S
x = Symbol ('x')
f = x - 5
xt = 2
print(f)
rlim = Limit(f,x,xt,dir='+').doit()
print("RHL : ", rlim)
llim = Limit(f,x,xt,dir='-').doit()
print("LHL : ", llim)
lim = Limit(f,x,xt).doit()
fc = xt - 5
if llim==rlim and lim==fc:
print("Function is continuous")
else:
print("Function is not continous")
print("\n")

x - 5
RHL : -3
LHL : -3
Function is continuous

d. f(x) = 2x + 7 at x = 0

In [54]: from sympy import Limit, Symbol, S


x = Symbol ('x')
f = 2*x + 7
xt = 0
print(f)
rlim = Limit(f,x,xt,dir='+').doit()
print("RHL : ", rlim)
llim = Limit(f,x,xt,dir='-').doit()
print("LHL : ", llim)
lim = Limit(f,x,xt).doit()
fc = 2*xt + 7
if llim==rlim and lim==fc:
print("Function is continuous")
else:
print("Function is not continous")
print("\n")

2*x + 7
RHL : 7
LHL : 7
Function is continuous

http://localhost:8889/notebooks/LAB%203.ipynb Page 15 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

e = f(x) = 5𝑥
3
+ 7𝑎𝑡𝑥 = 3

In [56]: from sympy import Limit, Symbol, S


x = Symbol ('x')
f = ((5*x)/3) + 7
xt = 3
print(f)
rlim = Limit(f,x,xt,dir='+').doit()
print("RHL : ", rlim)
llim = Limit(f,x,xt,dir='-').doit()
print("LHL : ", llim)
lim = Limit(f,x,xt).doit()
fc = ((5*xt)/3) + 7
if llim==rlim and lim==fc:
print("Function is continuous")
else:
print("Function is not continous")
print("\n")

5*x/3 + 7
RHL : 12
LHL : 12
Function is continuous

In [57]: #Alternate Method


from sympy import *
x = Symbol ('x')
xt = 2
print(f)
rlim = Limit(f,x,xt,dir='+').doit()
llim = Limit(f,x,xt,dir='-').doit()
f = simplify((x**2-4)/(x-2))
fc = f.subs({x:xt})
if llim==rlim==fc:
print("Function is continuous")
else:
print("Function is not continous")

5*x/3 + 7
Function is not continous

In [ ]:

http://localhost:8889/notebooks/LAB%203.ipynb Page 16 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM

http://localhost:8889/notebooks/LAB%203.ipynb Page 17 of 17
LAB 4 and LAB 5 - Jupyter Notebook 20/04/24, 8:42 PM

LAB 4

DEFINITION OF DERIVATIVES

Ther derivative of a function y = f(x) expresses the rate of change in the dependant
𝑑𝑦
variable y, with respect to the independant variable x. It is either denoted by f'(x) or 𝑑𝑥 .
We can find the derivative of a function by creating an objective of the derivative class

Example 1

Write a code to find the derivative of S(t) = 5𝑡2 + 2𝑡 + 8

In [1]: #Lim_{h->0} (f(x+h)-f(x))/h = f'(x)


#use the concept of limit to evaluate the derivative
from sympy import Symbol, Limit
t = Symbol('t')
St = 5*t**2 + 2*t + 8
t1 = Symbol('t1')
h = Symbol('h')
St_1 = St.subs({t:t1})
St1_h = St.subs({t:t1+h})
Limit((St1_h - St_1)/h,h,0).doit()

Out[1]: 10𝑡1 + 2

or by creating an object of the Derivative class:

In [2]: from sympy import Symbol, Derivative


t = Symbol('t')
St = 5*t**2 + 2*t + 8
Derivative(St,t)

(5𝑡 + 2𝑡 + 8)
Out[2]: 𝑑 2
𝑑𝑡

In [3]: d=Derivative(St,t)
d.doit()

Out[3]: 10𝑡 + 2

Now if we want to calculate the value of the derivative at a particular value of t, say t=t1
or t=1, we can use the subs() method

http://localhost:8889/notebooks/LAB%204%20and%20LAB%205.ipynb Page 1 of 7
LAB 4 and LAB 5 - Jupyter Notebook 20/04/24, 8:42 PM

In [4]: t1 = Symbol('t1')
d.doit().subs({t:t1})

Out[4]: 10𝑡1 + 2

In [5]: d.doit().subs({t:1})

Out[5]: 12

Example 2

(𝑥3 + 𝑥2 + 𝑥)(𝑥2 + 𝑥)

In [7]: x = Symbol('x')
f=(x**3 + x**2 + x)*(x**2+x)
Derivative(f,x)

(𝑥 + 𝑥) (𝑥 + 𝑥 + 𝑥)
Out[7]: 𝑑 2 3 2
𝑑𝑥

In [8]: d=Derivative(f,x)
d.doit()

Out[8]: (2𝑥 + 1) (𝑥3 + 𝑥2 + 𝑥) + (𝑥2 + 𝑥) (3𝑥2 + 2𝑥 + 1)

In [9]: d.doit().subs({x:1})

Out[9]: 21

Examples:
1.f(x) = 2x − 3/4
2.f(x) =$x^5(3-6x^-9)$
3.f(x) = sinxcosx
4.f(x) = 2tanx - 7secx
5.f(x) =$\frac{sinx}{x} + cosx$
6.f(x) =$e^x + e^y + e^x+y$
7.f(x) =$\frac{x}{1+x^2}$

http://localhost:8889/notebooks/LAB%204%20and%20LAB%205.ipynb Page 2 of 7
LAB 4 and LAB 5 - Jupyter Notebook 20/04/24, 8:42 PM

In [10]: from sympy import *


from sympy import Derivative
x = Symbol('x')
y = Symbol('y')
f1 = (sin(x)/x)+cos(x)
print(f1)
print(Derivative(f1,x).doit(),"\n")
f2 = exp(x) + exp(y) + exp(x**2 + y**2)
print(f2)
print(Derivative(f2,x).doit(),"\n")
f3 = x/(1+x**2)
print(f3)
print(Derivative(f3,x).doit(),"\n")
f4 = 2*tan(x) - 7*sec(x)
print(f4)
print(Derivative(f4,x).doit(),"\n")

cos(x) + sin(x)/x
-sin(x) + cos(x)/x - sin(x)/x**2

exp(x) + exp(y) + exp(x**2 + y**2)


2*x*exp(x**2 + y**2) + exp(x)

x/(x**2 + 1)
-2*x**2/(x**2 + 1)**2 + 1/(x**2 + 1)

2*tan(x) - 7*sec(x)
2*tan(x)**2 - 7*tan(x)*sec(x) + 2

Write a program for finding derivative of a user defined function.

In [11]: y = input("Enter the independent variable:")


y = Symbol(y)
f = eval(input("Enter a function in terms of the entered variable"))
d = Derivative(f,y)
print(d, "=",d.doit())

Enter the independent variable:x


Enter a function in terms of the entered variablex**3
Derivative(x**3, x) = 3*x**2

Finding maxima and minima

Find maxima and minima of the function 𝑥5 − 30𝑥3 + 50𝑥

http://localhost:8889/notebooks/LAB%204%20and%20LAB%205.ipynb Page 3 of 7
LAB 4 and LAB 5 - Jupyter Notebook 20/04/24, 8:42 PM

In [12]: from sympy import solve


x= Symbol('x')
f = x**5 - 30 * x**3 + 50*x
d=Derivative(f,x).doit()
f1=solve(d,x)
for i in f1:
print(float(i))
d2=Derivative(f,x,2).doit()
for i in f1:
f2 = d2.subs({x:i})
final = f.subs({x:i})
if(f2<0):
print ("Maxima at ", (float)(f2), " is ", (float)(final))
elif(f2>0):
print ("Minima at ", (float)(f2), " is ", (float)(final))
else:
print("Constant function")

-0.7575290270502124
0.7575290270502124
-4.1744640102863935
4.1744640102863935
Minima at 127.66106078907309 is -25.084662634029414
Maxima at -127.66106078907309 is 25.084662634029414
Maxima at -703.4931794681513 is 705.9594603803655
Minima at 703.4931794681513 is -705.9594603803655

In [13]: from sympy import solve


from sympy import Derivative
x= Symbol('x')
f = x**2 - 4
d=Derivative(f,x).doit()
f1=solve(d,x)
for i in f1:
print(float(i))
d2=Derivative(f,x,2).doit()
for i in f1:
f2 = d2.subs({x:i})
final = f.subs({x:i})
if(f2<0):
print ("Maxima at ", (float)(f2), " is ", (float)(final))
elif(f2>0):
print ("Minima at ", (float)(f2), " is ", (float)(final))
else:
print("Constant function")

0.0
Minima at 2.0 is -4.0

Plot the curve and its critical points

http://localhost:8889/notebooks/LAB%204%20and%20LAB%205.ipynb Page 4 of 7
LAB 4 and LAB 5 - Jupyter Notebook 20/04/24, 8:42 PM

In [14]: from matplotlib.pyplot import *


from numpy import *
from sympy import Symbol,solve,Derivative
#x = Symbol('x')
f = x**5 - 30 * x**3 + 50*x
d1=Derivative(f,x).doit()
f1=solve(d1)
a = linspace(-5,5)
b = a**5 - 30 * a**3 + 50*a
plot(a,b, color='pink')
for i in range(len(f1)):
plot(f1[i], f.subs({x:f1[i]}), color = 'black', marker = 'X')

Applications of derivatives

It is known that if y=f(x) , then the derivative can be interpreted as the rate of change of y
wrt x. Here, we examine the application of this idea to economins.

Cost Function

Consider a company which produced a certain commodity.C(x) Let be the total cost that
the company incurs in producing x units of the commondity, the function C is called the
cost function. The cost function is generally reprednted by the polynomial:
𝐶(𝑥) = 𝑎 + 𝑏𝑥 + 𝑐𝑥2 + 𝑑𝑥3 , where a represents the overhead cost like rent, heat,
maintainance, etc. (These factors are independent of x), represnets the cost of raw
materials etc. (these factors are directly proportional to x) and and represnt the labour
cost, overtime cost, and inefficiencis involved in large scale production(they are
represnted by higher powers of x)

http://localhost:8889/notebooks/LAB%204%20and%20LAB%205.ipynb Page 5 of 7
LAB 4 and LAB 5 - Jupyter Notebook 20/04/24, 8:42 PM

Introducing the concept of Marginal function (Using


CostFunction as an example)

If the number of items produced is increased from to , then the additional cost is , adn
the average rate of change of the cost is . The limit of the quantity as ∆x--> , that is the
instantaneous rate of change of cost with respect to the number of items produced, is
called the marginal cost by economists: marginal cost Since x is taken as an integer
value we can take in the literal sense taking and a very large we have Thus, the marginal
cost of producing units is approximately equal to the cost of producing one more unit
Cost Function C(x) C C(x) = a + bx + cx + d 2 x 3 x b x c d x x1 x2 ΔC = C(x2 ) − C(x1 ) =
= ΔC Δt C(x2)−C(x1) x2−x1 C(x1+Δx)−C(x1) Δx ∞ = limΔx→∞ = ΔC Δx dC dx limΔx→∞
Δx = 1 n C (n) ≅C(n + 1) − C(n). ′ n Suppose the a company has estimated that the
cost(in dollars) of producing items is: dollars. Sketch the graph of . Also verify whether
the marginal cost at the production level of 500 items is equal to the actual cost of
producing the item (i.e. verify x C(x) = 0.01x + 5x + 10000 2 C(x) 501 st C (n) = C(n + 1) −
C(n)

In [30]: import sympy


import matplotlib.pyplot as plt

In [35]: x = Symbol('x')
cx = 0.01*x**2+5*x+10000
print('C(x)=', cx)
marg_cost = diff(cx, x)
print("marginal cost=", marg_cost)
marg_cost_500 = marg_cost.evalf(subs={x:500})
print("marginal cost at 500 is ", marg_cost_500)
actual_cost_501 = cx.evalf(subs={x:501}) - cx.evalf(subs={x:500})
print("the actual cost of producing the 501st item is, ", actual_cost_5
if marg_cost_500 == round(actual_cost_501):
print("verified")

C(x)= 0.01*x**2 + 5*x + 10000


marginal cost= 0.02*x + 5
marginal cost at 500 is 15.0000000000000
the actual cost of producing the 501st item is, 15.0100000000002
verified

LAB 5

Revenue Fuctions

http://localhost:8889/notebooks/LAB%204%20and%20LAB%205.ipynb Page 6 of 7
LAB 4 and LAB 5 - Jupyter Notebook 20/04/24, 8:42 PM

In general, a business is concerned not only with its costs but also its revenues. Recall
that, if R(x) is the revenue recieved from the sales of units of commodity, then the
derivative R'(x) is called the marginal revenue per unit increase in sales. If units of product
are sold at a price p per unit, the total revenue R(x) is given by R(x)=x.p

Profit functions

Once we know the cost function C(x) and the revenue function R(x), we can compute the
profit function P(x) from P(x)=R(x)-C(x). Suppose that the demand equation for a
monopolist is p=100-0.1x and the cost function is C(x)=50x + 10,000 . Find marginal
profit

In [17]: x = Symbol('x')
p = 100 - 0.01*x
rx = x*p
cx = 50*x + 10000
px = rx - cx
mp = Derivative(px).doit()
print("the marginal profit is given by,", mp)

the marginal profit is given by, 50 - 0.02*x

A company can produce a maximum of 1500 widgets a year. If they sell x widgets a year,
𝑥3
their profit in dollars is given by, 𝑃 (𝑥) = 30000𝑥 + 750𝑥2 − 3
How many widgets
should they sell in order to maximise their profit?

In [34]: import sympy as sp


x = sp.Symbol('widgets')
P = 30000*x + 750*x**2 - x**3 / 3
d = sp.diff(P, x)
critical_points = sp.solve(d, x)
max_profit = P.subs({x: critical_points[1]})
print("The company should sell", critical_points[1], "widgets to maximi

The company should sell 750 + 50*sqrt(237) widgets to maximize the


ir profit.

In [ ]:

http://localhost:8889/notebooks/LAB%204%20and%20LAB%205.ipynb Page 7 of 7
LAB 6 - Jupyter Notebook 20/04/24, 8:43 PM

LAB 6

Differential Equations

𝑑𝑦
A differential equation is an equation of the form f(x,y, 𝑑𝑥 ....)

𝑑𝑦
1) Solve the differential equation 𝑑𝑥 =1

In [2]: from sympy import *


x = Symbol('x') # definding
y = Function('y')(x)
d = Eq(y.diff(x), 1) #
display(d)
dsolve(d, y)
𝑑
𝑦(𝑥) = 1
𝑑𝑥
Out[2]: 𝑦(𝑥) = 𝐶1 + 𝑥

𝑑𝑝
2) Solve 𝑑𝑡 −𝑟=0

In [3]: from sympy import *


t = Symbol("t") #defining independent variable
p = Function("p")(t) #defining dependent variable
r = Symbol("r")
D = Eq(p.diff(t,1)-r,0) #assigning differential equation
display(D)
dsolve(D,p)
𝑑
−𝑟 + 𝑝(𝑡) = 0
𝑑𝑡
Out[3]: 𝑝(𝑡) = 𝐶1 + 𝑟𝑡

𝑑2 𝑦 𝑑𝑦
3) Solve:
𝑑𝑥 2
+ 5 𝑑𝑥 + 6𝑦 = 0

http://localhost:8889/notebooks/LAB%206.ipynb Page 1 of 6
LAB 6 - Jupyter Notebook 20/04/24, 8:43 PM

In [4]: x = Symbol('x')
y = Function('y')(x)
d = Eq(y.diff(x,2)+5*y.diff(x)+6*y, 0)
display(d)
dsolve(d, y)

𝑑 𝑑2
6𝑦(𝑥) + 5 𝑦(𝑥) + 2 𝑦(𝑥) = 0
𝑑𝑥 𝑑𝑥
Out[4]: 𝑦(𝑥) = (𝐶1 + 𝐶2 𝑒−𝑥 ) 𝑒−2𝑥

𝑑3 𝑦
4) Solve =1
𝑑𝑥 3

In [5]: x = Symbol('x')
y = Function('y')(x)
d = Eq(y.diff(x,3)+y, 0)
display(d)
dsolve(d, y)

𝑑3
𝑦(𝑥) + 𝑦(𝑥) = 0
𝑑𝑥3
Out[5]: ⎯⎯ ⎯⎯

( ( 2 ) ( 2 ))
√3𝑥 √3𝑥 𝑥
𝑦(𝑥) = 𝐶3 𝑒−𝑥 + 𝐶1 sin + 𝐶2 cos 𝑒2

𝑑𝑝
5) Find the general solution for the given DE: 𝑑𝑡 − 𝑠𝑖𝑛(𝑡) − 𝑐𝑜𝑠(𝑡) and using that
determine the general solution when t = 1. And also determine the particular solution if
p(1) = 0.

http://localhost:8889/notebooks/LAB%206.ipynb Page 2 of 6
LAB 6 - Jupyter Notebook 20/04/24, 8:43 PM

In [6]: t = Symbol('t')
p = Function('p')(t)
D = Eq(p.diff(t,1)-(sin(t)+cos(t)),0)
print("The DE is: ")
display(D)
gen_sol = dsolve(D,p)
print("The general solution is: ")
display(gen_sol)
particular_sol = gen_sol.subs({t:1,p:0})
print("The particular solution is: ")
display(particular_sol)
from sympy import *
t = Symbol('t')
p = Function("p")(t)
r = Symbol('r')
D = Eq(p.diff(t,1)-sin(t)-cos(t),0)
print("Differential Equation : ")
display(D)
print("General Solution : ")
display( dsolve(D,p))
print("General Solution at t = 1 : ")
C1 = Symbol('C1')
display(dsolve(D,p).subs({t:1}))
print("Particular Solution : ")
display(dsolve(D,p).subs({C1 : cos(1)-sin(1)}))

The DE is:
𝑑
− sin (𝑡) − cos (𝑡) + 𝑝(𝑡) = 0
𝑑𝑡
The general solution is:

𝑝(𝑡) = 𝐶1 + sin (𝑡) − cos (𝑡)


The particular solution is:

0 = 𝐶1 − cos (1) + sin (1)


Differential Equation :

𝑑
− sin (𝑡) − cos (𝑡) + 𝑝(𝑡) = 0
𝑑𝑡
General Solution :

𝑝(𝑡) = 𝐶1 + sin (𝑡) − cos (𝑡)


General Solution at t = 1 :

𝑝(1) = 𝐶1 − cos (1) + sin (1)


Particular Solution :

𝑝(𝑡) = sin (𝑡) − cos (𝑡) − sin (1) + cos (1)

http://localhost:8889/notebooks/LAB%206.ipynb Page 3 of 6
LAB 6 - Jupyter Notebook 20/04/24, 8:43 PM

𝑑𝑓
6) Solve:
𝑑𝑥
= 5𝑓; 𝑓(2) = 10

In [7]: x = Symbol('x')
f = Function("f")(x)
D = Eq(f.diff(x,1),5*f)
print("Differential Equation : ")
display(D)
print("General Solution : ")
display(dsolve(D,f))
print("General Solution at t = 1 : ")
C1 = Symbol('C1')
display(dsolve(D,f).subs({x:2}))
print("Particular Solution : ")
display(dsolve(D,f).subs({C1 : 10/exp(10)}))

Differential Equation :
𝑑
𝑓(𝑥) = 5𝑓(𝑥)
𝑑𝑥
General Solution :

𝑓(𝑥) = 𝐶1 𝑒5𝑥
General Solution at t = 1 :

𝑓(2) = 𝐶1 𝑒10
Particular Solution :

10𝑒5𝑥
𝑓(𝑥) =
𝑒10

Particular solution of ode with constant coefficients

1. Solve the differential equation 𝑑 𝑃 (𝑡) = 𝑘𝑃 (𝑡) with the conditions


𝑑𝑥

P(0) = 18 P(2) = 39

http://localhost:8889/notebooks/LAB%206.ipynb Page 4 of 6
LAB 6 - Jupyter Notebook 20/04/24, 8:43 PM

In [9]: k = Symbol('k')
t = Symbol('t')
P = Function('P')(t)
eq = Eq(P.diff(t), k*P)
display(eq)
sol = dsolve(eq, P)
print("The general solution is: ")
display(sol)
Cx = sol.subs({t:0, P:18})
C_1 = Cx.lhs
print("C1=", C_1, sep="")
P_c1 = sol.subs(C1, C_1)
display(P_c1)
K = solve(P_c1.subs({t:2, P:39}), k)
display(K)
ps1 = P_c1.subs({k:K[0]})
ps2 = P_c1.subs({k:K[1]})
print("The particular solutions are: ")
display(ps1.subs(C1, C_1), ps2)
𝑑
𝑃 (𝑡) = 𝑘𝑃 (𝑡)
𝑑𝑡
The general solution is:

𝑃 (𝑡) = 𝐶1 𝑒𝑘𝑡
C1=18

𝑃 (𝑡) = 18𝑒𝑘𝑡
[-log(6) + log(78)/2, -log(6) + log(78)/2 + I*pi]

The particular solutions are:

𝑃 (𝑡) = 18𝑒 ( )
log (78)
𝑡 − log (6)+
2

𝑡(− log (6)+ +𝑖𝜋)


log (78)

𝑃 (𝑡) = 18𝑒 2

𝑑2 𝑦 𝑑𝑦
Solve the diferetial equation
𝑑𝑥 2
+ 2 𝑑𝑥 + 𝑦 = 0 with boundary conditions y(0)=1 and
y(1)=3

http://localhost:8889/notebooks/LAB%206.ipynb Page 5 of 6
LAB 6 - Jupyter Notebook 20/04/24, 8:43 PM

In [11]: x, k, C1, C2 = symbols('x, k, C1, C2')


y = Function('y')(x)
Px = y.diff(x, 2)+2*y.diff(x)+y
P = Eq(Px, 0)
display(P)
m = dsolve(Px, y)
display(m)
l = m.subs({x:0, y:1})
# display(l)
print("C1=",l.lhs)
l2 = m.subs({x:1, y:3, C1:l.lhs})
display(l2)
c2 = solve(l2)
# print(c2)
print("The particluar solutions are: ")
display(m.subs({C1:l.lhs, C2:c2[0]}))
#display(m.subs({C1:l.lhs, C2:c2[1]}))

𝑑 𝑑2
𝑦(𝑥) + 2 𝑦(𝑥) + 2 𝑦(𝑥) = 0
𝑑𝑥 𝑑𝑥
𝑦(𝑥) = (𝐶1 + 𝐶2 𝑥) 𝑒−𝑥
C1= 1

𝐶2 + 1
3=
𝑒
The particluar solutions are:

𝑦(𝑥) = (𝑥 (−1 + 3𝑒) + 1) 𝑒−𝑥

In [ ]:

http://localhost:8889/notebooks/LAB%206.ipynb Page 6 of 6
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

Topic 7

Consider a first order differential equation of the form y'=F(x,y) where F(x,y) is some
expression in x and y The differential equation says that the slope of a solution curve at
point (x,y) F(x,y) on the curve is . If we draw line segments with slope F(x,y) at several
points, is called a direction field (or a slope field) These line segments indicate the
direction in which a curve is heading, so the direction field helps us visualise the general
shape of these curves. In other words, a slope field for the first order equation
𝑑𝑦
𝑑𝑥
= 𝐹 (𝑥, 𝑦) is a plot of line segments with slopes for a lattice of points (x,y) in the
plane.

In [1]: import numpy as np


import matplotlib.pyplot as plt
from sympy import *
from mpl_toolkits import mplot3d

𝑑𝑦
Plot the slope field for 𝑑𝑥 =𝑥+𝑦

In [3]: x = np.arange(-3, 3, 0.3)


y = np.arange(-3, 3, 0.3)
X, Y = np.meshgrid(x, y) # return coordinate matrices from cooridnate v
dy = X + Y
dx = np.ones(dy.shape) # return a new array of given shape and type fil
color = dy
plot1 = plt.figure()
plt.quiver(X, Y, dx, dy, color="Blue") # quiver plot
plt.title("Slope field for y'=x+y")
plt.show(plot1)

http://localhost:8889/notebooks/LAB%207.ipynb Page 1 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

𝑑𝑦
Plot the slope fields for 𝑑𝑥 = xy

In [4]: x = np.arange(-3, 3, 0.3)


y = np.arange(-3, 3, 0.3)
X, Y = np.meshgrid(x, y) # return coordinate matrices from cooridnate v
dy = X * Y
dx = np.ones(dy.shape) # return a new array of given shape and type fil
color = dy
plot1 = plt.figure()
plt.quiver(X, Y, dx, dy, color="#a75b61") # quiver plot
plt.title("Slope field for y'=xy")
plt.show(plot1)

http://localhost:8889/notebooks/LAB%207.ipynb Page 2 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [5]: x = np.arange(-3, 3, 0.3)


y = np.arange(-3, 3, 0.3)
X, Y = np.meshgrid(x, y) # return coordinate matrices from cooridnate v
dy = np.sin(X)
dx = np.ones(dy.shape) # return a new array of given shape and type fil
color = dy
plot1 = plt.figure()
plt.quiver(X, Y, dx, dy, color="#fcba03") # quiver plot
plt.title("Slope field for y'=sinx")
plt.show(plot1)

http://localhost:8889/notebooks/LAB%207.ipynb Page 3 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [6]: x = np.arange(-3, 3, 0.3)


y = np.arange(-3, 3, 0.3)
X, Y = np.meshgrid(x, y) # return coordinate matrices from cooridnate v
dy = np.sin(X) + np.sin(Y)
dx = np.ones(dy.shape) # return a new array of given shape and type fil
color = dy
plot1 = plt.figure()
plt.quiver(X, Y, dx, dy, color="#b603fc") # quiver plot
plt.title("Slope field for y'=sinx+siny")
plt.show(plot1)

http://localhost:8889/notebooks/LAB%207.ipynb Page 4 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [7]: x = np.arange(-3, 3, 0.3)


y = np.arange(-3, 3, 0.3)
X, Y = np.meshgrid(x, y) # return coordinate matrices from cooridnate v
dy = 2*X
dx = np.ones(dy.shape) # return a new array of given shape and type fil
color = dy
plot1 = plt.figure()
plt.quiver(X, Y, dx, dy, color="#a5fc03") # quiver plot
plt.title("Slope field for y'=sinx")
plt.show(plot1)

http://localhost:8889/notebooks/LAB%207.ipynb Page 5 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [8]: x = np.arange(-3, 3, 0.3)


y = np.arange(-3, 3, 0.3)
X, Y = np.meshgrid(x, y) # return coordinate matrices from cooridnate v
dy = X ** 2
dx = np.ones(dy.shape) # return a new array of given shape and type fil
color = dy
plot1 = plt.figure()
plt.quiver(X, Y, dx, dy, color="#a5fc03") # quiver plot
plt.title("Slope field for y'=x^2")
plt.show(plot1)

http://localhost:8889/notebooks/LAB%207.ipynb Page 6 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [9]: x = np.arange(-3, 3, 0.3)


y = np.arange(-3, 3, 0.3)
X, Y = np.meshgrid(x, y) # return coordinate matrices from cooridnate v
dy = np.sin(Y)
dx = np.ones(dy.shape) # return a new array of given shape and type fil
color = dy
plot1 = plt.figure()
plt.quiver(X, Y, dx, dy, color="#a5fc03") # quiver plot
plt.title("Slope field for y'=siny")
plt.show(plot1)

http://localhost:8889/notebooks/LAB%207.ipynb Page 7 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [10]: x = np.arange(-3, 3, 0.3)


y = np.arange(-3, 3, 0.3)
X, Y = np.meshgrid(x, y) # return coordinate matrices from cooridnate v
dy = -1 * np.sin(Y)
dx = np.ones(dy.shape) # return a new array of given shape and type fil
color = dy
plot1 = plt.figure()
plt.quiver(X, Y, dx, dy, color="#a5fc03") # quiver plot
plt.title("Slope field for y'=-siny")
plt.show(plot1)

http://localhost:8889/notebooks/LAB%207.ipynb Page 8 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [11]: x = np.arange(-3, 3, 0.3)


y = np.arange(-3, 3, 0.3)
X, Y = np.meshgrid(x, y) # return coordinate matrices from cooridnate v
dy = np.sin(Y**2)
dx = np.ones(dy.shape) # return a new array of given shape and type fil
color = dy
plot1 = plt.figure()
plt.quiver(X, Y, dx, dy, color="#a5fc03") # quiver plot
plt.title("Slope field for y'=siny^2")
plt.show(plot1)

http://localhost:8889/notebooks/LAB%207.ipynb Page 9 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [12]: x = np.arange(-3, 3, 0.3)


y = np.arange(-3, 3, 0.3)
X, Y = np.meshgrid(x, y) # return coordinate matrices from cooridnate v
dy = np.sin(X) * np.cos(Y)
dx = np.ones(dy.shape) # return a new array of given shape and type fil
color = dy
plot1 = plt.figure()
plt.streamplot(X, Y, dx, dy, color=color, density=1, cmap="Pastel2", ar
plt.title("Slope field for y'=sin(x)cos(y)")
plt.show(plot1)

Plot slope field for


𝑑𝑦
𝑑𝑥
= 2(𝑠𝑖𝑛𝑦 + 𝑥)

http://localhost:8889/notebooks/LAB%207.ipynb Page 10 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [13]: x = np.arange(-10, 10, 0.3)


y = np.arange(-10, 10, 0.3)
X, Y = np.meshgrid(x, y) # return coordinate matrices from cooridnate v
dy = 2 * (np.sin(Y) + X)
dx = np.ones(dy.shape) # return a new array of given shape and type fil
color = dy
plot1 = plt.figure()
plt.streamplot(X, Y, dx, dy, color=color, density=1, cmap="gist_gray_r"
plt.title("Slope field for y'=2sin(y)+x")
plt.show(plot1)

𝑠𝑖𝑛(𝑥 2 +𝑦2 )
Plot the scalar field (x, y) =
𝑥 2 +𝑦2

http://localhost:8889/notebooks/LAB%207.ipynb Page 11 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [14]: import numpy as np


import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
x=np.linspace(-np.pi,np.pi,200)
y=np.linspace(-np.pi,np.pi,200)
X,Y = np.meshgrid(x,y)
Z = (np.sin(X**2 + Y**2)/(X**2 + Y**2))
fig = plt.figure()
ax=plt.axes(projection = '3d')
abc = ax.plot_surface(X,Y,Z,cmap='ocean')
ax.set_xlabel('$X$')
ax.set_ylabel('$Y$')
ax.set_zlabel('$Z$')
fig.colorbar(abc,shrink=0.7,aspect=5)
ax.set_title("Scalar Field")
plt.show()

http://localhost:8889/notebooks/LAB%207.ipynb Page 12 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [15]: x=np.linspace(-np.pi,np.pi,200)
y=np.linspace(-np.pi,np.pi,200)
X,Y = np.meshgrid(x,y)
Z = X**2
fig = plt.figure()
ax=plt.axes(projection = '3d')
abc = ax.plot_surface(X,Y,Z,cmap='Reds')
ax.set_xlabel('$X$')
ax.set_ylabel('$Y$')
ax.set_zlabel('$Z$')
fig.colorbar(abc,shrink=0.7,aspect=5)
ax.set_title("Scalar Field 1")
plt.show()

http://localhost:8889/notebooks/LAB%207.ipynb Page 13 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [16]: x=np.linspace(-np.pi,np.pi,200)
y=np.linspace(-np.pi,np.pi,200)
X,Y = np.meshgrid(x,y)
Z = np.sin(Y)
fig = plt.figure()
ax=plt.axes(projection = '3d')
abc = ax.plot_surface(X,Y,Z,cmap='PuRd')
ax.set_xlabel('$X$')
ax.set_ylabel('$Y$')
ax.set_zlabel('$Z$')
fig.colorbar(abc,shrink=0.7,aspect=5)
ax.set_title("Scalar Field 2")
plt.show()

http://localhost:8889/notebooks/LAB%207.ipynb Page 14 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM

In [17]: x=np.linspace(-np.pi,np.pi,200)
y=np.linspace(-np.pi,np.pi,200)
X,Y = np.meshgrid(x,y)
Z = - np.sin(Y)
fig = plt.figure()
ax=plt.axes(projection = '3d')
abc = ax.plot_surface(X,Y,Z,cmap='Purples')
ax.set_xlabel('$X$')
ax.set_ylabel('$Y$')
ax.set_zlabel('$Z$')
fig.colorbar(abc,shrink=0.7,aspect=5)
ax.set_title("Scalar Field 3")
plt.show()

-3-2

http://localhost:8889/notebooks/LAB%207.ipynb Page 15 of 15
LAB 8. - Jupyter Notebook 20/04/24, 8:43 PM

LAB 8

Interest Rates

Simple Interest = 𝑃𝑇𝑅


100

compound interest = 𝑃 . [(1 + 100


𝑟 𝑡
) − 1]

compound interest (anually) = 𝑃 (𝑒( 𝑟𝑡) − 1)

In [10]: from sympy import symbols, solve, Eq


from math import e
p = float(input("Enter amount:"))
t = float(input("Enter time: "))
r = float(input("Enter rate:"))
si = (p*t*r/100)
ci = p*((1 + r/100)**t)
print("Simple interest is: ", si)
print("Compound interest is: ", ci)

Enter amount:1000
Enter time: 10
Enter rate:5
Simple interest is: 500.0
Compound interest is: 1628.894626777442

In a bank, principal increases continuously at the rate of 5% per year. An amount of


Rs.1000 is deposited with the bank. How much will it be worth after 10 years.

In [11]: p = float(input("Enter amount:"))


t = float(input("Enter time: "))
r = float(input("Enter rate:"))
si = (p*t*r/100)
ci = p*((1 + r/100)**t)
print("Simple interest is: ", si)
print("Compound interest is: ", ci)

Enter amount:1000
Enter time: 10
Enter rate:4
Simple interest is: 400.0
Compound interest is: 1480.2442849183444

http://localhost:8889/notebooks/LAB%208..ipynb Page 1 of 4
LAB 8. - Jupyter Notebook 20/04/24, 8:43 PM

How much time does it take for a given amount of money to double at 10% per annum
compounded a) annually b) continously

In [15]: from sympy import solve


p, t = symbols('p, t')
ci = p*((1 + 10/100)**t)
cci = p*(e**(0.1*t)-1)
cid = solve(ci-2*p, t)
ccid = solve(cci-2*p, t)
print("When compounded annually, t =", cid)
print("When compounded continuously, t =", ccid)

------------------------------------------------------------------
---------
NotImplementedError Traceback (most recent c
all last)
Input In [15], in <cell line: 6>()
4 cci = p*(e**(0.1*t)-1)
5 cid = solve(ci-2*p, t)
----> 6 ccid = solve(cci-2*p, t)
7 print("When compounded annually, t =", cid)
8 print("When compounded continuously, t =", ccid)

File ~/opt/anaconda3/lib/python3.9/site-packages/sympy/solvers/sol
vers.py:1106, in solve(f, *symbols, **flags)
1102 #
1103 # try to get a solution
1104
#######################################################################
1105 if bare_f:
-> 1106 solution = _solve(f[0], *symbols, **flags)
1107 else:
1108 solution = _solve_system(f, symbols, **flags)

File ~/opt/anaconda3/lib/python3.9/site-packages/sympy/solvers/sol
vers.py:1720, in _solve(f, *symbols, **flags)
1717 # ----------- end of fallback ----------------------------
1719 if result is False:
-> 1720 raise NotImplementedError('\n'.join([msg, not_impl_msg
% f]))
1722 if flags.get('simplify', True):
1723 result = list(map(simplify, result))

NotImplementedError: multiple generators [20000000000000**(t/10),


54365636569181**(t/10)]
No algorithms are implemented to solve equation p*((5436563656918
1/20000000000000)**(t/10) - 1) - 2*p

http://localhost:8889/notebooks/LAB%208..ipynb Page 2 of 4
LAB 8. - Jupyter Notebook 20/04/24, 8:43 PM

How long does it take for a given amount of money to triple at 10% p.a. compounded
annually

In [4]: p, t = symbols('p, t')


ci = p*((1 + 10/100)**t)
cid = solve(ci-3*p, t)
print("When compounded annually, t =", cid)

When compounded annually, t = [11.5267046072476]

In a bank, principle increases continuously at the rate of r% per year. Find the value of r if
Rs.100 doubles itself in 100 years.

In [23]: import sympy


p = 100
t = 100
r = sympy.Symbol("rate")
ci = p * sympy.exp(r * t / 100)
equ = sympy.Eq(ci, 2 * p)
result = sympy.solve([equ], (t,))
print("The value of r is:", result,"%")

The value of r is: {100: 200*exp(-rate)} %

How long does it take for a given amount of money to double at 15% p.a. compounded
continuously:

In [25]: import math


p = 100
r = 15
t = sympy.Symbol("time")
ci = p * math.e ** (r * t / 100)
equ = sympy.Eq(ci, 2 * p)
result = sympy.solve([equ], (t,))
print("It takes", result[0][0], "years for the amount to double.")

It takes 4.62098120373296 years for the amount to double.

Steve deposited Rs. 9000 in a bank and after 10 years, he closed the bank account,
which is worth 18,000. What is the rate of interest over 10 years?

http://localhost:8889/notebooks/LAB%208..ipynb Page 3 of 4
LAB 8. - Jupyter Notebook 20/04/24, 8:43 PM

In [8]: p = 9000
t = 10
ci = 18000
r = symbols("rate")
equ = Eq(p * 2.72**(r * t / 100), ci)
result = solve([equ], (r,))
print("The rate of interest is:", result[0][0], "%")

The rate of interest is: 6.92709471086066 %

In [ ]:

http://localhost:8889/notebooks/LAB%208..ipynb Page 4 of 4
LAB 9 and LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

LAB 9

Exponential models- Population growth model

A growth model of a population represents the dynamics where the population's growth
rate increases over time, in proportion of the size of the population. Let p denote the
population of a species. Since poulation increases with respect to time, p is a function of
𝑑𝑝
time t. Let 𝑑𝑡 denote the rate of growth of the population. Since the rate of the growth of
the population depends on the amount of population present, Where k=0 is known as the
constant of proportionality

In [1]: from sympy import *


import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

Q1. If the population of a town increased from 50,000 to 100,000 in five years, find the
population of a town after 10 years.

In [2]: t, k, C1 = symbols('t, k, C1')


p = Function('p')(t)
dif = Eq(p.diff(t), k*p)
display(dif)
sol = dsolve(dif, p)
display(sol)
c1 = sol.subs({p:50000, t:0}).lhs
p5 = sol.subs({p:100000, t:5, C1:c1})
k0 = solve(p5, k)
final_sol = sol.subs({C1:c1, k:k0[4]})
display(final_sol)
p10 = solve(final_sol.subs({t:10}))
p10[0]
𝑑
𝑝(𝑡) = 𝑘𝑝(𝑡)
𝑑𝑡
𝑝(𝑡) = 𝐶1 𝑒𝑘𝑡

𝑝(𝑡) = 50000𝑒𝑡 log (√2)


5

Out[2]: {p(10): 200000}

Q2. If the population of a city doubled in 25 years from 100000, how long will it take to
reach 500000.

http://localhost:8889/notebooks/LAB%209%20and%20LAB%2010.ipynb Page 1 of 9
LAB 9 and LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

In [3]: t, k, C1 = symbols('t, k, C1')


p = Function('p')(t)
dif = Eq(p.diff(t), k*p)
display(dif)
sol = dsolve(dif, p)
display(sol)
c1 = sol.subs({p:100000, t:0}).lhs
p5 = sol.subs({p:200000, t:25, C1:c1})
k0 = solve(p5, k)
final_sol = sol.subs({C1:c1, k:k0[4]})
display(final_sol)
t5_0 = solve(final_sol.subs({p:500000}))
float(t5_0[0])
𝑑
𝑝(𝑡) = 𝑘𝑝(𝑡)
𝑑𝑡
𝑝(𝑡) = 𝐶1 𝑒𝑘𝑡

𝑝(𝑡) = 100000𝑒𝑡 log ( √2)


25

Out[3]: 58.04820237218406

Q3. A bacteria culture starts with 1000 bacteria and doubles in size every 3 hours. Find
an exponential model for the size of the culture as a function of time in t hours?

In [4]: t, k, C1 = symbols('t, k, C1')


p = Function('p')(t)
dif = Eq(p.diff(t), k*p)
display(dif)
sol = dsolve(dif, p)
display(sol)
c1 = sol.subs({p:1000, t:0}).lhs
p5 = sol.subs({p:2000, t:3, C1:c1})
k0 = solve(p5, k)
final_sol = sol.subs({C1:c1, k:k0[2]})
display(final_sol)

𝑑
𝑝(𝑡) = 𝑘𝑝(𝑡)
𝑑𝑡
𝑝(𝑡) = 𝐶1 𝑒𝑘𝑡

𝑝(𝑡) = 1000𝑒𝑡 log (√2)


3

Q4. The frog population in a small pond grows exponentially. The currect population is 85
frogs, and the relative growth rate is 18% per year. a) FInd a function that models the
number of frogs after t years. b) FInd the projected population after 3 years. c) Find the
number of years required for the frog population to reach 600.

http://localhost:8889/notebooks/LAB%209%20and%20LAB%2010.ipynb Page 2 of 9
LAB 9 and LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

In [5]: t, k, C1 = symbols('t, k, C1')


p = Function('p')(t)
dif = Eq(p.diff(t), k*p)
display(dif)
sol = dsolve(dif, p)
display(sol)
c1 = sol.subs({p:85, t:0}).lhs
p5 = sol.subs({p:1.18*85, t:1, C1:c1})
k0 = solve(p5, k)[0]
final_sol = sol.subs({C1:c1, k:k0})
print("\na) ", end='')
display(final_sol)
p10 = solve(final_sol.subs({t:3}))
print("\nb) ", end='')
display(p10[0])
𝑑
𝑝(𝑡) = 𝑘𝑝(𝑡)
𝑑𝑡
𝑝(𝑡) = 𝐶1 𝑒𝑘𝑡

a)

𝑝(𝑡) = 85𝑒0.165514438477573𝑡

b)

{p(3): 139.657720000000}

LAB 10

Mathematical model for logistic Growth

Modifying the equation for exponential growth, using k(per capita growth rate) that
depends on population size(P) and how close it is to carrying capacity(N). Therefore we
𝑑𝑝
xan write the following equation: 𝑑𝑡 = 𝑘𝑃 ( 𝑁 ) where, N-P tells us how many
𝑁−𝑃

𝑁−𝑃
individuals can be added before it hits carrying capacity. 𝑁 is the fraction of the
carrying capacity that has not yet been used up. The more carrying capacity that has
𝑁−𝑃
been used up, the more the term 𝑁
will reduce the growth rate.

Q1. Biologists stock a lake with 500 fish and estimate the carrying capacity to be 10,000.
The number of fish increased by 3 times during the fisrt year. Assuming that the size if the
fish population satistfies the logistic equation, find population after t years.

http://localhost:8889/notebooks/LAB%209%20and%20LAB%2010.ipynb Page 3 of 9
LAB 9 and LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

In [6]: def h(P, t):


eq = k*P*(1-P/10000)
return eq
k = 3
P0 = 500
t = np.linspace(0, 20, 10)
P2 = odeint(h, P0, t)
plt.plot(t, P2, marker='o')
None

Q2. A researcher stocks a tank with 18 and estimate the carrying capacity to be 700. The
number of yeast increased by 0.733 times during the first year. Find the population after t
years.

http://localhost:8889/notebooks/LAB%209%20and%20LAB%2010.ipynb Page 4 of 9
LAB 9 and LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

In [8]: def h(P, t):


eq = k*P*(1-P/700)
return eq
k = 0.773
P0 = 18
t = np.linspace(0, 20, 10)
P2 = odeint(h, P0, t)
plt.plot(t, P2, marker='o', color='k')
None

Q3. A researcher stocks a tank with 18 and estimate the carrying capacity to be 700. The
number of yeast increased by 0.395 times during the first year. Find the population after t
years.

http://localhost:8889/notebooks/LAB%209%20and%20LAB%2010.ipynb Page 5 of 9
LAB 9 and LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

In [9]: def h(P, t):


eq = k*P*(1-P/700)
return eq
k = 0.395
P0 = 18
t = np.linspace(0, 20, 100)
P2 = odeint(h, P0, t)
plt.plot(t, P2, marker='o', color='k')

Out[9]: [<matplotlib.lines.Line2D at 0x7f91721b7be0>]

Q4. Biologists stock 50 bacterias and estimate the carrying capacity to be 1000.
Assuming that the growth of bacteria satisfies the logistic equation, find the population
after t years. For the following growth rates: a)0.39, b)0.535, c)0.409.

http://localhost:8889/notebooks/LAB%209%20and%20LAB%2010.ipynb Page 6 of 9
LAB 9 and LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

In [10]: def h(P, t):


eq = k1*P*(1-P/1000)
return eq
def i(P, t):
eq = k2*P*(1-P/1000)
return eq
def j(P, t):
eq = k3*P*(1-P/1000)
return eq
k1 = 0.39
k2 = 0.535
k3 = 0.409
P0 = 50
t = np.linspace(0, 20, 10)
P1 = odeint(h, P0, t)
P2 = odeint(i, P0, t)
P3 = odeint(j, P0, t)
plt.plot(t, P1, marker='o')
plt.plot(t, P2, marker='o')
plt.plot(t, P3, marker='o')
plt.title("Logistic Model of growth of bacteria with different k values"
plt.xlabel("Time")
plt.ylabel("Population of Bacteria")
plt.legend(['a logistic model with k=0.39','a logistic model with k=0.53
plt.show()

Q6. The following table shows the number of yeast in the new lab
Time(hrs)|0|2|4|6|8|10|12|14|16|18| Yeast cells|18|39|80|171|336|509|597|597|640|664|672|

In [12]: # From Data


plt.subplot(2, 2, 1)
x = [0,2,4,6,8,10,12,14,16,18]
y = [18, 39, 80, 171, 336, 509, 597, 640, 664,672]
plt.title("From data")

http://localhost:8889/notebooks/LAB%209%20and%20LAB%2010.ipynb Page 7 of 9
LAB 9 and LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

plt.xlabel("Population")
plt.ylabel("Time")
plt.grid(True)
plt.plot(x, y, color="purple")
# Exponential
plt.subplot(2, 2, 2)
def h(P, t):
eq = k*P
return eq
P0 = 18
k = 0.168
t = np.linspace(0, 20, 10)
plt.ylabel("Population")
plt.xlabel("Number of Years")
P1 = odeint(h, P0, t)
plt.title("Exponential Growth")
plt.xlabel("Population")
plt.ylabel("Time")
plt.grid(True)
plt.plot(t, P1, marker="o", color='mediumpurple')
# Logistic
plt.subplot(2, 2, 3)
def h(P, t):
eq = k*P*(1-P/700)
return eq
k = 0.386
P0 = 18
t = np.linspace(0, 20, 10)
P2 = odeint(h, P0, t)
plt.title("Logistic Growth")
plt.xlabel("Population")
plt.ylabel("Time")
plt.grid(True)
plt.plot(t, P2, marker='o', color='navy')
# Combined
plt.subplot(2,2,4)
plt.title("Comparision")
plt.xlabel("Population")
plt.ylabel("Time")
plt.grid(True)
plt.plot(x, y, marker='o', color="purple")
plt.plot(t, P2, marker='.', color='mediumpurple')
plt.plot(t,P1,marker = '*', color='navy')
plt.legend(["Data", "Exponential", "Logistic"])

Out[12]: <matplotlib.legend.Legend at 0x7f917245fe80>

http://localhost:8889/notebooks/LAB%209%20and%20LAB%2010.ipynb Page 8 of 9
LAB 9 and LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

Data
Exponential

Logistic

http://localhost:8889/notebooks/LAB%209%20and%20LAB%2010.ipynb Page 9 of 9
LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

LAB 11

Motion of a simple pendulum

program to simulate the transient behaviour of a simple pendulum. The governing


principle behind the simple movement of a pendulum can be broken down
mathematically using a simple ordinary differential equations given by:
𝑑2 𝜃 𝑔
𝑑𝑡 2
+ ( 𝑚𝑏 ) 𝑑𝜃
𝑑𝑡
+ ( 𝑙 )𝑠𝑖𝑛(𝜃) = 0 where, 𝜃 = angle between vertical and the string of
the pendulum , b=damping coefficient, m=mass of bob, g=accleration due to gravity
, l=length of the pendulum

In [3]: import numpy as np


import matplotlib.pyplot as plt
from scipy.integrate import odeint
import math

#defining the function for ODE


def model(theta,t,b,g,l,m):
theta1=theta[0]
theta2=theta[1]
dtheta_1=theta2
dtheta_2=(b/m)*theta2-(g/l)*math.sin(theta1)
dtheta_dt=[dtheta_1,dtheta_2]
return dtheta_dt

#initiallizing important parameters


# damping coefficient
b=0.0
#length of the string
l=1
#accleration due to gravity
g=9.81
#mass of the bob
m=0.1
#initial condition
theta_0=[0,5]
# time points
t=np.linspace(0,10,150)
#solveing ode by function call
theta=odeint(model,theta_0,t,args=(b,g,l,m))

#plotting the results for transient behaviour


plt.figure
plt.plot(t,theta[:,0],'b-',label=r'$\frac{d\theta_1}{dt}=\theta_2$')
plt.plot(t,theta[:,1],'r--',label=r'$\frac{d\theta_2}{dt}=\frac{b}{m}\t
plt.ylabel('Plot')
plt.xlabel('time')

http://localhost:8889/notebooks/LAB%2010%20.ipynb#LAB-11 Page 1 of 4
LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

plt.legend(loc='best')
plt.show
None

Conclusion:

program to simulate the motion of the mass on the spring The governing proinciple
behind the simple movement of a pendulum can be broken down mathematically using a
2
simple ode given by : 𝑚 𝑑 𝑥2
𝑑𝑡
+ 𝑎 𝑑𝑥
𝑑𝑡
+ 𝑘𝑥 = 𝐹 (𝑡) where,

x displacement of the mass from the equillibrium position,


m=mass of the object at the end of the string(kgs)
k=spring constant, Newtons per metre
a=damping coefficient , Newton*second/meter

2
for a free, undamped motion 𝑑 𝑥2
𝑑𝑡
+ 𝑘
𝑚
𝑥 =0
𝑑2 𝑥
for a free, damped motion 𝑚 2
𝑑𝑡
+ 𝑎 𝑑𝑥
𝑑𝑡
+ 𝑘𝑥 = 0
𝑑𝑡2 𝑥
for forced motion 𝑚 2 + 𝑎 𝑑𝑥
𝑑𝑡
+ 𝑘𝑥 = 𝐹 (𝑡)
𝑑𝑡

Example: 𝐹 (𝑡) = 𝑐𝑜𝑠(4 ∗ 𝑡 − 𝑝𝑖/4)

http://localhost:8889/notebooks/LAB%2010%20.ipynb#LAB-11 Page 2 of 4
LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

In [1]: def MassSpringDamper(state,t):


k=0.81 # spring constant
m=64.2 # mass,kg
a=3 #damping coefficient
# unpack the state vector
x,xd=state #displacement , x and velocity x'
#g=9.8 # metres per second**2
#compute acceleration edd=x''
#omega=1.0 # phase shift
# A=5.0 # amplitude
xdd=-k*x/m -(a/m)*xd + math.cos(4*t-math.pi/4)/m
return [xd,xdd]

In [4]: state0=[0.0,1.2] #initial conditions [x0,v0] [m,m/sec]


ti=0.0 #initial time
tf=4.0 #final tme
step=0.001 #step
t=np.arange(ti,tf,step)
state=odeint(MassSpringDamper,state0,t)
x=np.array(state[:,[0]])
xd=np.array(state[:,[1]])

In [7]: def MassSpringDamper(state,t):


k=124e3
m=64.2
a=3
x,xd=state
xdd=-k*x/m-(a/m)*xd+math.cos(4*t-math.pi/4)/m
return[xd,xdd]

state0=[0.0,1.2]
t1=0.0
tf=4.0
step=0.001
t=np.arange(t1,tf,step)
state=odeint(MassSpringDamper,state0,t)
x=np.array(state[:,[0]])
xd=np.array(state[:,[1]])
plt.rcParams['figure.figsize']=(15,12)
plt.rcParams['font.size']=18
fig,ax1=plt.subplots()
ax2=ax1.twinx()
ax1.plot(t,x*1e3,'b',label=r'$x (mm)$', linewidth=2.0)
ax2.plot(t,xd,'g--',label=r'$\dot{x} (m/sec)$', linewidth=2.0)
ax2.legend(loc='lower right')
ax1.legend()
ax1.set_xlabel('time (sec)')
ax1.set_ylabel('disp (mm)', color='b')
ax2.set_ylabel('velocity (m/s)', color='g')
plt.title('Mass-Spring System with $V_0=1.2 \frac{m}{s}$ and $\delta_(m
plt.grid()

http://localhost:8889/notebooks/LAB%2010%20.ipynb#LAB-11 Page 3 of 4
LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM

disp(mm)

In [ ]:
x(m/

http://localhost:8889/notebooks/LAB%2010%20.ipynb#LAB-11 Page 4 of 4
LAB 12 - Jupyter Notebook 20/04/24, 8:50 PM

LAB 12

SIR model

Mathematical model S(t)=how many individuals , at time t, that have the possibility to get
infected where t may count for hours/days. These individuals make category called
susceptibles,labelled as S. I(t)=count how many there are that are infected These
individuals make category called infected , labelled as I at time t. An infected individual
having recovered from the disease is assumed to gain immunity.There is also a small
possibility that an infected wiill die. In either case, the individual is moved from the I
category to a category we call removed category,labelled with R. R(t)=count the number
of individuals in the R category at time t.Those who enter the R category , cannot leave
this category,cannot leave this category. The SIR model describes the change in the
population of each of these compartments in termds of two parameters ,β and γ. β
describes the effective contact rate of the disease: an infected individual comes in
contact with βN other individuals per unit time(of which the fraction that are susceptible
to contracting the disease is γis the mean recovery rate: is the mean period of time
during which an infected individual can pass it on. The following python code integrates
these equations for a disease characterised by parameters.β=0.2 and days in a
population of N=1000(perhaps flu in school). The model is started with a single infected
individual on day 0:I(0)=1. Th eplotted cureves S(t),I(t)and R(t) are styled to look a bit nicer
than matplotlib's defaults.

http://localhost:8889/notebooks/LAB%2012.ipynb Page 1 of 3
LAB 12 - Jupyter Notebook 20/04/24, 8:50 PM

In [4]:import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

N = 1000
I0, R0 = 1, 0
S0 = N - I0 - R0
beta, gamma = 0.2, 1./10
t = np.linspace(0, 160, 160)
def deriv(y,t,N,beta,gamma):
S,I,R = y
dSdt = -beta*S*I/N
dIdt = beta*S*I/N - gamma * I
dRdt = gamma * I
return dSdt, dIdt, dRdt
y0 = S0, I0, R0
ret = odeint(deriv, y0, t, args=(N,beta,gamma))
S,I,R = ret.T
fig = plt.figure(facecolor='w')
ax = fig.add_subplot(111, facecolor='#dddddd', axisbelow=True)
ax.plot(t, S/1000, 'b', alpha=0.5, lw=2, label='Susceptible')
ax.plot(t, I/1000, 'r', alpha=0.5, lw=2, label='Infected')
ax.plot(t, R/1000, 'g', alpha=0.5, lw=2, label='Recovered with immunity'
ax.set_xlabel('Time /days')
ax.set_ylabel('Number (1000s)')
ax.set_ylim(0,1.2)
ax.yaxis.set_tick_params(length=0)
ax.xaxis.set_tick_params(length=0)
ax.grid(visible=True, which='major', c='w', lw=2, ls='-')
legend = ax.legend()
legend.get_frame().set_alpha(0.5)
for spine in ('top','right','bottom','left'):
ax.spines[spine].set_visible(False)
plt.show()

Susceptible
Infected
Recoveredwithimmunity
Number(1000s)

0.2

80 100 120 140 160


ime/days

http://localhost:8889/notebooks/LAB%2012.ipynb Page 2 of 3
LAB 12 - Jupyter Notebook 20/04/24, 8:50 PM

In [ ]:

http://localhost:8889/notebooks/LAB%2012.ipynb Page 3 of 3

You might also like