E-Record 2240449
E-Record 2240449
MAT451
PYTHON E - Record
Sreshta P
2240449
INDEX
Topic Page No
LAB 2-Plot
2D Plott
In [2]: import numpy as np
import matplotlib.pyplot as plt
http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 1 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM
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
/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()
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)
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')
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")
http://localhost:8888/notebooks/LAB%202-Plot.ipynb Page 10 of 16
LAB 2-Plot - Jupyter Notebook 20/04/24, 8:42 PM
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
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 [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 [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 [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")
In [58]: sin(pi/2)
x = Symbol('x')
y = sin(x)
y
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
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
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.
Out[14]: ℎ
1
Using the formula for equations of motion S = ut + 2 𝑎𝑡2 , derieve the equation for
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
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
Out[17]: 𝑦2 + 3𝑦 − 8
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
def g(y):
func_gy = 2*y+5
return func_gy
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
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
Out[90]: 𝑥2 + 𝑒𝑥 − 18
1. sum
2. difference
3. product
4. quotient
5. composition
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]: 𝑒
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
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
http://localhost:8889/notebooks/LAB%203.ipynb Page 10 of 17
LAB 3 - Jupyter Notebook 20/04/24, 8:42 PM
Out[41]: ∞
Out[42]: −∞
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
True
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
Function is continuous
Function is continuous
Function is continuous
Function is continuous
Function is continuous
Function is discontinuous
Continuity:
𝑥 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
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
5*x/3 + 7
RHL : 12
LHL : 12
Function is continuous
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
Out[1]: 10𝑡1 + 2
(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()
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
cos(x) + sin(x)/x
-sin(x) + cos(x)/x - sin(x)/x**2
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
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
-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
0.0
Minima at 2.0 is -4.0
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
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
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 [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")
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)
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 [ ]:
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
𝑑𝑝
2) Solve 𝑑𝑡 −𝑟=0
𝑑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:
𝑑
− sin (𝑡) − cos (𝑡) + 𝑝(𝑡) = 0
𝑑𝑡
General Solution :
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
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]
𝑃 (𝑡) = 18𝑒 ( )
log (78)
𝑡 − log (6)+
2
𝑃 (𝑡) = 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
𝑑 𝑑2
𝑦(𝑥) + 2 𝑦(𝑥) + 2 𝑦(𝑥) = 0
𝑑𝑥 𝑑𝑥
𝑦(𝑥) = (𝐶1 + 𝐶2 𝑥) 𝑒−𝑥
C1= 1
𝐶2 + 1
3=
𝑒
The particluar solutions are:
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.
𝑑𝑦
Plot the slope field for 𝑑𝑥 =𝑥+𝑦
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
http://localhost:8889/notebooks/LAB%207.ipynb Page 2 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM
http://localhost:8889/notebooks/LAB%207.ipynb Page 3 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM
http://localhost:8889/notebooks/LAB%207.ipynb Page 4 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM
http://localhost:8889/notebooks/LAB%207.ipynb Page 5 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM
http://localhost:8889/notebooks/LAB%207.ipynb Page 6 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM
http://localhost:8889/notebooks/LAB%207.ipynb Page 7 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM
http://localhost:8889/notebooks/LAB%207.ipynb Page 8 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM
http://localhost:8889/notebooks/LAB%207.ipynb Page 9 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM
http://localhost:8889/notebooks/LAB%207.ipynb Page 10 of 15
LAB 7 - Jupyter Notebook 20/04/24, 8:43 PM
𝑠𝑖𝑛(𝑥 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
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
Enter amount:1000
Enter time: 10
Enter rate:5
Simple interest is: 500.0
Compound interest is: 1628.894626777442
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
------------------------------------------------------------------
---------
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))
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 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.
How long does it take for a given amount of money to double at 15% p.a. compounded
continuously:
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], "%")
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
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
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.
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
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?
𝑑
𝑝(𝑡) = 𝑘𝑝(𝑡)
𝑑𝑡
𝑝(𝑡) = 𝐶1 𝑒𝑘𝑡
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
a)
𝑝(𝑡) = 85𝑒0.165514438477573𝑡
b)
{p(3): 139.657720000000}
LAB 10
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
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
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
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
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|
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"])
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
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,
2
for a free, undamped motion 𝑑 𝑥2
𝑑𝑡
+ 𝑘
𝑚
𝑥 =0
𝑑2 𝑥
for a free, damped motion 𝑚 2
𝑑𝑡
+ 𝑎 𝑑𝑥
𝑑𝑡
+ 𝑘𝑥 = 0
𝑑𝑡2 𝑥
for forced motion 𝑚 2 + 𝑎 𝑑𝑥
𝑑𝑡
+ 𝑘𝑥 = 𝐹 (𝑡)
𝑑𝑡
http://localhost:8889/notebooks/LAB%2010%20.ipynb#LAB-11 Page 2 of 4
LAB 10 - Jupyter Notebook 20/04/24, 8:44 PM
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
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