Python MAC-4
Python MAC-4
Python MAC-4
( Numerical Analysis
using PYTHON )
Department -- PHYSICS
Sem. -- II
Reg. No. -- A01-1152 -111- 002 -
2023
Admit Roll. -- 2024121009
1
INDEX
Page
Contents No.
Collatz Conjecture 3
ⅆ𝒚
Solving ODE : + 𝟐𝒚 − (ⅇ−𝒙 ) = 𝟎 7
ⅆ𝒙
ⅆ𝒚
Solving ODE :- + 𝒚𝟐 = 𝟏 9
ⅆ𝒙
Radioactive Disintegration 11
Euler Method 13
Gravitational Problem 16
2
-: Collatz Conjecture :-
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("classic")
xf=100000
xx2,yy2=[],[]
for j in range(5,xf+1):
xx2.append(j)
m=j
n=0
while(m!=1):
n+=1
if m%2==0:
m=m/2
else:
m=3*m+1
yy2.append(n)
point=np.argmax(yy2)-1
y=point
xx1,yy1=[],[]
i=0
while(y!=1):
i+=1
if y%2==0:
y=y/2
yy1.append(y)
else:
y=3*y+1
3
yy1.append(y)
xx1.append(i)
yy4=[np.log(x) for x in yy1]
xx3,yy3=[],[]
for k in range(max(yy2)):
s=yy2.count(k)
yy3.append(s)
xx3.append(k)
fig,ax=plt.subplots(2,2,figsize=(10,10),constrained_layout=True)
ax[0,0].plot(xx1,yy1,"Black")
ax[0,0].set_title(f"Collatz Sequence of {point}")
ax[0,0].text(point,max(yy1),f"{max(yy1)}")
ax[0,0].grid(True)
ax[0,0].axvline(x=0,alpha=0.5)
ax[0,0].axhline(y=0,alpha=0.5)
ax[0,0].set_xlabel("steps no. $\\rightarrow$" )
ax[0,0].set_ylabel("step value $\\rightarrow$")
ax[0,1].plot(xx2,yy2,'--',color="red")
ax[1,0].plot(xx3,yy3,'--',color="blue")
slope,intercept=np.polyfit(xx1,yy4,1)
xx_fit=np.linspace(min(xx1),max(xx1),100)
yy_fit=slope*xx_fit+intercept
ax[1,1].plot(xx1,yy4,"black")
ax[1,1].plot(xx_fit,yy_fit)
ax[1,1].set_title(f"log distribution curve of {point}")
4
ax[1,1].axvline(x=0,alpha=0.5)
ax[1,1].axhline(y=0,alpha=0.5)
ax[1,1].set_xlabel("steps no. $\\rightarrow$" )
ax[1,1].set_ylabel("ln(step value) $\\rightarrow$")
ax[0,1].hist(xx2,weights=yy2,bins=range(2,xf+2),color="red")
ax[0,1].text(point+5,max(yy2)-15,f"maximum steps= {max(yy2)} at {point} ")
ax[0,1].set_title("Collatz_length of series of numbers")
ax[0,1].set_xlabel("seed no. $\\rightarrow$" )
ax[0,1].set_ylabel("Collatz Length $\\rightarrow$")
maxf=max(yy3)
most_step=np.argmax(yy3)
ax[1,0].hist(xx3,weights=yy3,bins=range(1,max(xx3)+1),color="blue")
ax[1,0].set_title(f"Frequency distribution upto {xf}")
ax[1,0].text(most_step+10,maxf-80,f"most probable steps= {most_step} of frequency=
{maxf}")
ax[1,0].set_xlabel("no. of steps $\\rightarrow$" )
ax[1,0].set_ylabel("Frequency $\\rightarrow$")
plt.show()
5
-: Output :-
6
ⅆ𝒚
-: Solving ODE :- + 𝟐𝒚 − (ⅇ−𝒙 ) = 𝟎
ⅆ𝒙
import matplotlib.pyplot as plt
import numpy as np
def f(x,y): #define the ODE
y1=np.exp(-x)-2*y
y2=np.exp(-x)-np.exp(-2*x)
return y1,y2
xi=0
xf=5
y=0
n=500
h=(xf-xi)/(n-1)
xx,yy1,yy2=[],[],[]
for i in range (n):
y1,y2=f(xi,y)
y=y+h*y1
yy1.append(y)
yy2.append(y2)
xx.append(xi)
xi=xi+h
plt.plot(xx,yy1,'-.',label='Plot of ODE',color="red")
plt.plot(xx,yy2,'--',label="real sol.",color="green")
plt.axvline(x=0,color='Black')
plt.axhline(y=0,color='Black')
plt.grid(True)
plt.title(" Solving ODE: $ \\frac{dy}{dx} + 2y-e^{{-x}} = 0 $")
plt.ylabel("y(x)$\\rightarrow$")
7
plt.xlabel("x$\\rightarrow$")
plt.legend(loc='best',fontsize=10)
plt.show()
-: Output :-
8
ⅆ𝒚
-: Solving ODE :- + 𝒚𝟐 = 𝟏
ⅆ𝒙
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
e=np.exp
y1=1-y**2 # given ODE
y2=(e(2*x)-1)/(e(2*x)+1) # known solution of ODE
return y1,y2
xi=0
xf=3
y=0
n=10000
h=(xf-xi)/(n-1)
xx,yy1,yy2=[],[],[]
for i in range (n):
x=xi+i*h
y1,y2=f(x,y)
y=y+h*y1
yy1.append(y)
yy2.append(y2)
xx.append(x)
plt.plot(xx,yy1,'-.',label='Plot of ODE',color="red")
plt.plot(xx,yy2,'--',label="real sol.",color="green")
plt.axvline(x=0,color='Black')
plt.axhline(y=0,color='Black')
plt.grid(True)
plt.title("solve ODE")
9
plt.ylabel("y(x)$\\rightarrow$")
plt.xlabel("x$\\rightarrow$")
plt.legend(loc='best',fontsize=10)
plt.show()
-: Output :-
10
-: Radioactive Disintegration :-
import matplotlib.pyplot as plt
import numpy as np
11
yy3.append(x3)
tt.append(t)
ss.append(s)
plt.plot(tt,yy1,'-.',label="$N_A(t)$",color="red")
plt.plot(tt,yy2,'--',label="$N_B(t)$",color="green")
plt.plot(tt,yy3,':',label="$N_C(t)$",color="blue")
plt.plot(tt,ss,'-',label="N",color="brown")
plt.axvline(x=0,color='Black')
plt.axhline(y=0,color='Black')
plt.grid(True)
plt.title("Radioactive Disintegration")
plt.ylabel("N(t) $\\rightarrow$")
plt.xlabel("Time(t) $\\rightarrow$")
plt.legend(loc='best',fontsize=15)
plt.show()
-: Output :-
12
-: Euler Method :-
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
pi=np.pi
x1=(-pi*y)
y1=(pi*x)
return x1,y1
ti=0
tf=4
x=1
y=0
n=10000
h=(tf-ti)/(n-1)
tt,xx,yy=[],[],[]
for i in range (n):
t=ti+i*h
x1,y1=f(x,y)
y=y+h*y1
x=x+h*x1
yy.append(y)
xx.append(x)
tt.append(t)
fig,ax=plt.subplots(2,1,figsize=(8,8),constrained_layout=True)
ax[0].plot(tt,xx,'-.',color="red")
ax[0].plot(tt,yy,'--',color="green")
ax[0].axvline(x=0,color='Black')
ax[0].axhline(y=0,color='Black')
ax[0].grid(True)
13
ax[0].set_ylabel("y(t) or x(t)$\\rightarrow$")
ax[0].set_xlabel("time$\\rightarrow$")
ax[0].set_title("Plot of y(t) vs time & x(t) vs time")
ax[1].plot(xx,yy,'--',color="green")
ax[1].axvline(x=0,color='Black')
ax[1].axhline(y=0,color='Black')
ax[1].grid(True)
ax[1].set_ylabel("y(t)$\\rightarrow$")
ax[1].set_xlabel("x(t)$\\rightarrow$")
ax[1].set_title("Plot of y(t) vs x(t)")
plt.show()
14
-: Output :-
15
-: Gravitational Problem :-
import matplotlib.pyplot as plt
import numpy as np
def f(x,v,t):
if x==1:
return (-g-r*v)
elif x==-1:
return (g-r*v)
elif x==2:
return (-g-r*v**2)
elif x==-2:
return (g-r*v**2)
g=9.8
r=5
u1=10
u2=0
h=10**(-4)
t=0
tt1,tt2,tt3,tt4,vv1,vv2,vv3,vv4=[],[],[],[],[],[],[],[]
x=1
while (u1>=0):
u1=u1+h*f(x,u1,t)
tt1.append(t)
t=t+h
vv1.append(u1)
t=0
x=-1
16
while (f(x,u2,t)>=g/1000):
u2=u2+h*f(x,u2,t)
tt2.append(t)
t=t+h
vv2.append(u2)
u1=10
u2=0
t=0
x=2
while (u1>=0):
u1=u1+h*f(x,u1,t)
tt3.append(t)
t=t+h
vv3.append(u1)
t=0
x=-2
while (f(x,u2,t)>=g/1000):
u2=u2+h*f(x,u2,t)
tt4.append(t)
t=t+h
vv4.append(u2)
fig,ax=plt.subplots(2,2,figsize=(4,4),constrained_layout=True)
17
ax[0][0].axvline(x=0)
ax[0][0].axhline(y=0)
ax[0][0].set_xlabel("Time $\\rightarrow$" )
ax[0][0].set_ylabel("Velocity $\\rightarrow$")
18
ax[1][1].set_ylabel("Velocity $\\rightarrow$")
plt.show()
-: Output :-
19
-: Bisection Method (Root Finding) :-
import matplotlib.pyplot as plt
import numpy as np
def f(x):
return np.exp(-x)*(3.2*np.sin(x)-0.5*np.cos(x))
def fn(a,b,h,n):
xx,yy=[],[]
for i in range (n):
x=a+i*h
y=f(x)
xx.append(x)
yy.append(y)
return xx,yy
a=0
b=6
xi=3
xf=4
n=1000
h=(b-a)/(n-1)
xx,yy=fn(a,b,h,n)
d=10**(-5)
while abs(xf-xi)>=d:
if f(xi)*f(xf)<0:
c=(xf+xi)/2
if f(c)*f(xf)<0:
xi=c
elif f(c)*f(xf)>0:
xf=c
plt.scatter(c,f(c))
plt.text(c, f(c), f"{c:.3f},{f(c):.3f}")
20
plt.plot(xx,yy,color="red")
plt.axvline(x=0,color='Black')
plt.axhline(y=0,color='Black')
plt.grid(True)
plt.title("root of a function: $e^{-x} \\left( 3.2\\sin{(x)}-0.5\\cos{(x)} \\right) $")
plt.ylabel("y(x)$\\rightarrow$")
plt.xlabel("x$\\rightarrow$")
plt.show()
-: Output :-
21
-: Transient Phenomena of RC Circuit :-
import numpy as np
import matplotlib.pyplot as plt
def f(vc):
return (vi-vc)/(R*C)
vi=10
R= 1000
C= 100e-6
t=0
vc=0
tf=0.5
n=10000
h=(tf-t)/(n-1)
Vc,T=[],[]
while vc<=vi*0.999:
Vc.append(vc)
T.append(t)
t=t+h
vc=vc+f(vc)*h
22
-: Output :-
23
-: Determine Area of common Section
enclosed by Sin(x) & Cos(x) :-
import numpy as np
def f(x):
y1=np.sin(x)
y2=np.cos(x)
if y1>=y2:
return y2
else:
return y1
yy=[]
xi=0
xf=np.pi/2
n=1000
s=0
h=(xf-xi)/(n-1)
for i in range(0,n):
x=xi+i*h
y=f(x)
yy.append(y)
for i in range(1,n-1):
s=s+2*yy[i]
s=s+yy[0]+yy[n-1]
m=s*h/2
m=round(m,5)
print(m)
Output:
My Codes/2nd sem/integration.py"
0.58579
24
-: Newton Raphson Method :-
import numpy as np
def f(x):
return (x**3-4)
def fn(x):
return (f(x+h)-f(x))/h
i=0
x=4
h=1e-8
while abs(f(x)>h):
x=x-f(x)/fn(x)
i+=1
print(i,x)
-: Output :-
My Codes/2nd sem/Newton Raphson.py"
6 1.5874010520322663
25