[go: up one dir, main page]

0% found this document useful (0 votes)
19 views21 pages

Maths Colab

The document contains various Python code snippets utilizing the SymPy library for symbolic mathematics, including integration, divergence, curl, and beta and gamma functions. Each code block performs specific mathematical operations and prints the results, often including user input for parameters. The document also demonstrates the use of NumPy for linear algebra operations, such as finding the rank and null space of matrices.
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)
19 views21 pages

Maths Colab

The document contains various Python code snippets utilizing the SymPy library for symbolic mathematics, including integration, divergence, curl, and beta and gamma functions. Each code block performs specific mathematical operations and prints the results, often including user input for parameters. The document also demonstrates the use of NumPy for linear algebra operations, such as finding the rank and null space of matrices.
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/ 21

from sympy import *

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


w1= integrate(x ** 2+y ** 2 ,(y,0,x),(x,0,1))
print (w1)
print("Snehashree M AI DS 4GW24AD053")

1/3
Snehashree M AI DS 4GW24AD053

from sympy import *


x= Symbol('x')
y= Symbol('y')
z= Symbol('z')
w2= integrate((x*y*z),(z,0,3-x-y),(y,0,3-x),(x,0,3))
print (w2)
print("Snehashree M AI DS 4GW24AD053")

81/80
Snehashree M AI DS 4GW24AD053

from sympy import *


x= Symbol('x')
y= Symbol('y')
#a= Symbol ('a ')
#b= Symbol ('b ')
a=4
b=6
w3=4* integrate(1,(y,0,(b/a)* sqrt (a ** 2-x ** 2)),(x,0,a))
print (w3)
print("Snehashree M AI DS 4GW24AD053")

24.0*pi
Snehashree M AI DS 4GW24AD053

from sympy import *


r= Symbol('r')
t= Symbol('t')
a= Symbol('a')
#a=4
w3=2* integrate(r,(r,0,a*(1+cos (t))),(t,0,pi))
pprint(w3)
print("Snehashree M AI DS 4GW24AD053")

2
3⋅π⋅a
──────
2
Snehashree M AI DS 4GW24AD053

from sympy import *


x= Symbol('x')
y= Symbol('y')
z= Symbol('z')
a= Symbol('a')
b= Symbol('b')
c= Symbol('c')
w2= integrate(1,(z,0,c*(1-x/a-y/b)),(y,0,b*(1-x/a)),(x,0,a))
print (w2)
print("Snehashree M AI DS 4GW24AD053")

a*b*c/6
Snehashree M AI DS 4GW24AD053

import numpy as np
import matplotlib.pyplot as plt
import math
from sympy import *
r= Symbol('r')
t= Symbol('t')
a= Symbol('a')
I1= integrate(cos (t)*r ** 2 ,(r,0,a*(1+cos (t))),(t,-pi ,pi))
I2= integrate(r,(r,0,a*(1+cos (t))),(t,-pi ,pi))
I=I1/I2
print (I)
I=I.subs(a,5)
# Removed the trailing space from 'polar '
plt.axes(projection = 'polar')
a=5
rad = np. arange (0,(2 * np.pi),0.01)
# plotting the cardioid
for i in rad :
r = a + (a*np.cos(i)) # Indent this line
plt.polar(i,r,'g.') # Indent this line
plt.polar(0,I,'r.')
plt.show()
print("Snehashree M AI DS 4GW24AD053")

5*a/6

from sympy import *


x= symbols('x')
w1= integrate(exp (-x),(x,0, float ('inf ')))
print ( simplify(w1))
print("Snehashree M AI DS 4GW24AD053")

1
Snehashree M AI DS 4GW24AD053

from sympy import *


x= symbols('x')
w1= integrate(exp (-x)*x ** 4 ,(x,0, float ('inf ')))
print ( simplify(w1))
print("Snehashree M AI DS 4GW24AD053")

24
Snehashree M AI DS 4GW24AD053

# Install or upgrade mpmath


!pip install --upgrade mpmath

from sympy import *


from IPython.display import display # Ensure display is imported

# Define symbols s and t


s, t = symbols('s t')

# Perform the integration


w1 = integrate(exp(-s * t) * cos(4 * t), (t, 0, oo))

# Simplify and display the result


# If the AttributeError persists, you might try simplifying without
# the rational conversion if possible, or inspecting the result of integrate(..)
# before simplification to see its structure. However, the most likely issue
# is with the mpmath installation.
try:
simplified_w1 = simplify(w1)
display(simplified_w1)
except AttributeError as e:
print(f"AttributeError during simplification: {e}")
print("Trying to display the unsimplified result:")
display(w1)

print("Snehashree M AI DS 4GW24AD053")
# The second block of code in the original cell is redundant and can be removed
# s, t = symbols('s t')
# w1 = integrate(exp(-s * t) * cos(4 * t), (t, 0, oo))
# display(simplify(w1))
# print("Aishwarya AC 4GW24AD002")

Requirement already satisfied: mpmath in /usr/local/lib/python3.11/dist-packages


⎧ s2 +16
s
for ∣arg (s)∣ < π

⎨ ∞ −st
2
​ ​

⎩ ∫ e cos (4t) dt otherwise


​ ​ ​

0
Snehashree M AI DS 4GW24AD053
Double-click (or enter) to edit

from sympy import beta,gamma


m= input ('m :');
n= input ('n :');
m= float (m);
n= float (n);
s= beta(m,n);
t= gamma(n)
print ('gamma (',n,') is %3.3f '%t)
print ('Beta (',m,n,') is %3.3f '%s)
print("Snehashree M AI DS 4GW24AD053")

m :6
n :2
gamma ( 2.0 ) is 1.000
Beta ( 6.0 2.0 ) is 0.024
Snehashree M AI DS 4GW24AD053

from sympy import beta,gamma


m= float ( input ('m : '));
n= float ( input ('n :'));
s= beta(m,n);
t= gamma(n)
print ('gamma (',n,') is %3.3f '%t)
print ('Beta (',m,n,') is %3.3f '%s)
print("Snehashree M AI DS 4GW24AD053")

m : 4
n :5
gamma ( 5.0 ) is 24.000
Beta ( 4.0 5.0 ) is 0.004
Snehashree M AI DS 4GW24AD053

from sympy.vector import *


from sympy import symbols
N= CoordSys3D('N')
x,y,z= symbols('x y z')
A=N.x ** 2*N.y*N.z*N.i+N.y ** 2*N.z*N.x*N.j+N.z ** 2*N.x*N.y*N.k
delop =Del()
divA = delop.dot (A)
display(divA)
print (f"\n Divergence of {A} is \n")
display(divergence(A))
print("Snehashree M AI DS 4GW24AD053")
∂ ∂ ∂
xN yN zN 2 + xN yN 2 zN + xN 2 yN zN
∂zN ∂yN ∂xN
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​

​ ​ ​

Divergence of N.x**2*N.y*N.z*N.i + N.x*N.y**2*N.z*N.j + N.x*N.y*N.z**2*N.k is

6xN yN zN
​ ​ ​

Snehashree M AI DS 4GW24AD053

from sympy import beta,gamma


m=5;
n=7;
m= float (m);
n= float (n);
s= beta(m,n);
t=( gamma(m)* gamma(n))/ gamma(m+n);
print (s,t)
if (abs (s-t)<=0.00001):
print ('beta and gamma are related ')
else :
print ('given values are wrong ')
print("Snehashree M AI DS 4GW24AD053")

0.000432900432900433 0.000432900432900433
beta and gamma are related
Snehashree M AI DS 4GW24AD053

from sympy.vector import *


from sympy import symbols
N= CoordSys3D('N')
x,y,z= symbols('x y z')
A=N.x ** 2*N.y*N.z*N.i+N.y ** 2*N.z*N.x*N.j+N.z ** 2*N.x*N.y*N.k
delop =Del()
curlA = delop.cross(A)
display(curlA)
print (f"\n Curl of {A} is \n")
display(curl(A))
print("Snehashree M AI DS 4GW24AD053")
∂ ∂ ∂ ∂
( xN yN zN 2 − xN yN 2 zN ) ^iN + (− xN yN zN 2 + xN 2 yN zN ) ^jN +
∂yN ∂zN ∂xN ∂zN
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​

​ ​ ​ ​

∂ ∂
( xN yN 2 zN − xN 2 yN zN ) k^N
∂xN ∂yN
​ ​ ​ ​ ​ ​ ​ ​ ​

​ ​

Curl of N.x**2*N.y*N.z*N.i + N.x*N.y**2*N.z*N.j + N.x*N.y*N.z**2*N.k is

(−xN yN 2 + xN zN 2 ) ^iN + (xN 2 yN − yN zN 2 ) ^jN + (−xN 2 zN + yN 2 zN ) k


​ ​ ​ ​ ​
^N ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​

Snehashree M AI DS 4GW24AD053

from sympy.physics.vector import *


from sympy import var,pprint
var('x,y,z')
v= ReferenceFrame('v')
F=v[0] ** 2*v[1]*v[2]
G= gradient(F,v)
F=F.subs([(v[0],x),(v[1],y),(v[2],z)])
print (" Given scalar function F=")
display(F)
G=G.subs([(v[0],x),(v[1],y),(v[2],z)])
print ("\n Gradient of F=")
display(G)
print("Snehashree M AI DS 4GW24AD053")

Given scalar function F=


x2 yz

Gradient of F=
^ x + x2 z v
2xyz v ^ y + x2 y v
^z
​ ​ ​

Snehashree M AI DS 4GW24AD053

from sympy.physics.vector import *


from sympy import var
var('x,y,z')
v= ReferenceFrame('v')
F=v[0] ** 2*v[1]*v.x+v[1]*v[2] ** 2*v.y+v[0] ** 2*v[2]*v.z
G= divergence(F,v)
F=F.subs([(v[0],x),(v[1],y),(v[2],z)])
print (" Given vector point function is ")
display(F)
G=G.subs([(v[0],x),(v[1],y),(v[2],z)])
print (" Divergence of F=")
display(G)
print("Snehashree M AI DS 4GW24AD053")
Given vector point function is
x2 y v
^x + yz 2 v

^ y + x2 z v

^z ​

Divergence of F=
x2 + 2xy + z 2
Snehashree M AI DS 4GW24AD053

from sympy.physics.vector import *


from sympy import var
var('x,y,z')
v= ReferenceFrame('v')
F=v[0]*v[1] ** 2*v.x+2*v[0] ** 2*v[1]*v[2]*v.y-3*v[1]*v[2] ** 2*v.z
G= curl(F,v)
F=F.subs([(v[0],x),(v[1],y),(v[2],z)])
print (" Given vector point function is ")
display(F)
G=G.subs([(v[0],x),(v[1],y),(v[2],z)])
print (" curl of F=")
display(G)
print("Snehashree M AI DS 4GW24AD053")

Given vector point function is


xy 2 v
^x + 2x2 yz v

^y − 3yz 2 v

^z ​

curl of F=
(−2x2 y − 3z 2 )v
^x + (4xyz − 2xy)v

^z ​

Snehashree M AI DS 4GW24AD053

import numpy as np
from scipy.linalg import null_space
# Define a linear transformation interms of matrix
A = np. array ([[1,2,3], [4,5,6], [7,8,9]])
# Find the rank of the matrix A
rank = np.linalg.matrix_rank(A)
print (" Rank of the matrix ",rank)
# Find the null space of the matrix A
ns = null_space(A)
print (" Null space of the matrix ",ns)
# Find the dimension of the null space
nullity = ns. shape [1]
print (" Null space of the matrix ",nullity)
# Verify the rank - nullity theorem
if rank + nullity == A. shape [1]:
print ("Rank - nullity theorem holds .")
else :
print ("Rank - nullity theorem does not hold .")
print("Snehashree M AI DS 4GW24AD053")

Rank of the matrix 2


Null space of the matrix [[-0.40824829]
[ 0.81649658]
[-0.40824829]]
Null space of the matrix 1
Rank - nullity theorem holds .
Snehashree M AI DS 4GW24AD053
import numpy as np
# Define the vector space V
V = np. array ([
[1,2,3],
[2,3,1],
[3,1,2]])
# Find the dimension and basis of V
basis = np.linalg.matrix_rank(V)
dimension = V. shape [0]
print (" Basis of the matrix ",basis)
print (" Dimension of the matrix ",dimension)
print("Snehashree M AI DS 4GW24AD053")

Basis of the matrix 3


Dimension of the matrix 3
Snehashree M AI DS 4GW24AD053

from numpy import *


import sympy as sp
A=[[1,-1,1,1],[2,-5,2,2],[3,-3,5,3],[4,-4,4,4]]
AB= array (A)
S= shape (A)
n=len(A)
for i in range (n):
if AB[i,i]==0:
ab= copy (AB)
for k in range (i+1,S[0]):
if ab[k,i]!=0:
ab[i,:]=AB[k,:]
ab[k,:]=AB[i,:]
AB= copy (ab)
for j in range (i+1,n):
if AB[i, i] != 0:
Fact =AB[j,i]/AB[i,i]
for k in range (i,n):
AB[j,k]=AB[j,k]- Fact *AB[i,k]
else:
display("REF of given matrix : ",sp.Matrix(AB))
temp = {(0,0,0,0)}
result = []
for idx,row in enumerate (map(tuple , AB)):
if row not in temp :
result. append (idx)
print ("\n Basis are non - zero rows of A:")
display(sp.Matrix(AB[ result ]))
print("Snehashree M AI DS 4GW24AD053")
'REF of given matrix : '
1 −1 1 1
2 −5 2 2
3 −3 5 3
​ ​ ​ ​ ​ ​

4 −4 4 4

Basis are non - zero rows of A:


1 −1 1 1
2 −5 2 2
3 −3 5 3
​ ​ ​ ​ ​ ​

4 −4 4 4
Snehashree M AI DS 4GW24AD053

import numpy as np
import matplotlib.pyplot as plt
V = np. array ([[10,0]])
origin = np. array ([[0,0,0],[0,0,0]]) # origin point
A=np.matrix([[2,0],[0,1]])
V1=np.matrix(V)
V2=A*np.transpose(V1)
V2=np. array (V2)
plt.quiver(*origin,V[:,0], V[:,1], color =['b'], scale =50)
plt.quiver(*origin,V2[0,:], V2[1,:], color =['r'], scale =50)
plt.show()
print("Snehashree M AI DS 4GW24AD053")

import numpy as np
import matplotlib.pyplot as plt
V = np. array ([[10,0]])
origin = np. array ([[0,0,0],[0,0,0]]) # origin point
A=np.matrix([[-1,0],[0,1]])
V1=np.matrix(V)
V2=A*np.transpose(V1)
V2=np. array (V2)
plt.quiver(*origin,V[:,0], V[:,1], color =['b'], scale =50)
plt.quiver(*origin,V2[0,:], V2[1,:], color =['r'], scale =50)
plt.show()
print("Snehashree M AI DS 4GW24AD053")
import numpy as np
import matplotlib.pyplot as plt
V = np. array ([[10,0]])
origin = np. array ([[0,0,0],[0,0,0]]) # origin point
A=np.matrix([[0,-1],[1,1]])
V1=np.matrix(V)
V2=A*np.transpose(V1)
V2=np. array (V2)
plt.quiver(*origin,V[:,0], V[:,1], color =['b'], scale =50)
plt.quiver(*origin,V2[0,:], V2[1,:], color =['r'], scale =50)
plt.show()
print("Snehashree M AI DS 4GW24AD053")

import numpy as np
import matplotlib.pyplot as plt
V = np. array ([[2,3]])
origin = np. array ([[0,0,0],[0,0,0]]) # origin point
A=np.matrix([[1,2],[0,1]])
V1=np.matrix(V)
V2=A*np.transpose(V1)
V2=np. array (V2)
print (" Image of given vectors is:", V2)
plt.quiver(*origin,V[:,0], V[:,1], color =['b'], scale =20)
plt.quiver(*origin,V2[0,:], V2[1,:], color =['r'], scale =20)
plt.show()
print("Snehashree M AI DS 4GW24AD053")

Image of given vectors is: [[8]


[3]]

import numpy as np
import matplotlib.pyplot as plt
V = np. array ([[2,3]])
origin = np. array ([[0,0,0],[0,0,0]]) # origin point
A=np.matrix([[0,-1],[1,0]])
B=np.matrix([[2,0],[0,1]])
V1=np.matrix(V)
V2=A*np.transpose(V1)
V3=B*V2
V2=np. array (V2)
V3=np. array (V3)
print (" Image of given vectors is:", V3)
plt.quiver(*origin,V[:,0], V[:,1], color =['b'], scale =20)
plt.quiver(*origin,V2[0,:], V2[1,:], color =['r'], scale =20)
plt.quiver(*origin,V3[0,:], V3[1,:], color =['g'], scale =20)
plt.title('Blue = original , Red = Rotated ,Green = Rotated + Streached ')
plt.show()
print("Snehashree M AI DS 4GW24AD053")

Image of given vectors is: [[-6]


[ 2]]
import numpy as np
# initialize arrays
A = np. array ([2,1,5,4])
B = np. array ([3,4,7,8])
#dot product
output = np. dot(A,B)
print ( output)
print("Snehashree M AI DS 4GW24AD053")

77
Snehashree M AI DS 4GW24AD053

import numpy as np
# initialize arrays
A = np. array ([2,1,5,4])
B = np. array ([3,4,7,8])
#dot product
output = np. dot(A,B)
print ('Inner product is :',output)
if output ==0:
print ('given vectors are orthognal ')
else :
print ('given vectors are not orthognal')
print("Snehashree M AI DS 4GW24AD053")

Inner product is : 77
given vectors are not orthognal
Snehashree M AI DS 4GW24AD053

from sympy import *

x = Symbol('x')
g = sympify(input('Enter the function: ')) # sympify to convert input to sympy expression
f = lambdify(x, g)
dg = diff(g)
df = lambdify(x, dg)

x0 = float(input('Enter the initial approximation: '))


n = int(input('Enter the number of iterations: '))

for i in range(1, n + 1):


# Check if the derivative at x0 is close to zero
if abs(df(x0)) < 1e-9: # Use a small tolerance to check for near-zero
print(f"Error: Derivative is zero or very close to zero at x = {x0}. Newton-Raphson
break # Exit the loop if derivative is zero

x1 = x0 - (f(x0) / df(x0))
print('iteration %d \t the root %.3f \t function value %.3f \n' % (i, x1, f(x1)))
x0 = x1

# Only print the final root if the loop completed without a zero derivative error
if i == n and abs(df(x0)) >= 1e-9:
print('\nFinal value of the root after %d iterations is %.5f' % (n, x0))

print("Snehashree M AI DS 4GW24AD053")
Enter the function: 5
Enter the initial approximation: 6
Enter the number of iterations: 3
Error: Derivative is zero or very close to zero at x = 6.0. Newton-Raphson metho
Snehashree M AI DS 4GW24AD053

from sympy import *

x = Symbol('x')
g = sympify(input('Enter the function: ')) # sympify to convert input to sympy expression
f = lambdify(x, g)
dg = diff(g)
df = lambdify(x, dg)

x0 = float(input('Enter the initial approximation: '))


n = int(input('Enter the number of iterations: '))

for i in range(1, n + 1):


# Check if the derivative at x0 is close to zero
if abs(df(x0)) < 1e-9: # Use a small tolerance to check for near-zero
print(f"Error: Derivative is zero or very close to zero at x = {x0}. Newton-Raphson
break # Exit the loop if derivative is zero

x1 = x0 - (f(x0) / df(x0))
print('iteration %d \t the root %.3f \t function value %.3f \n' % (i, x1, f(x1)))
x0 = x1

# Only print the final root if the loop completed without a zero derivative error
if i == n and abs(df(x0)) >= 1e-9:
print('\nFinal value of the root after %d iterations is %.5f' % (n, x0))

print("Snehashree M AI DS 4GW24AD053")

Enter the function: 4


Enter the initial approximation: 3
Enter the number of iterations: 4
Error: Derivative is zero or very close to zero at x = 3.0. Newton-Raphson metho
Snehashree M AI DS 4GW24AD053

from sympy import *


import numpy as np
n = int( input ('Enter number of data points : '))
210
x = np. zeros ((n))
y = np. zeros ((n,n))
# Reading data points
print ('Enter data for x and y: ')
for i in range (n):
x[i] = float ( input ( 'x['+str(i)+']= '))
y[i][0] = float ( input ( 'y['+str(i)+']= '))
# Generating forward difference table
for i in range (1,n):
for j in range (0,n-i):
y[j][i] = y[j+1][i-1] - y[j][i-1]
print ('\ nFORWARD DIFFERENCE TABLE \n');
for i in range (0,n):
print ('%0.2f ' %(x[i]),end='')
for j in range (0,n-i):
print ('\t\t%0.2f ' %(y[i][j]),end='')
print ()
# obtaining the polynomial
t= symbols('t')
f=[] # f is a list type data
p=(t-x[0])/(x[1]-x[0])
f. append (p)
for i in range (1,n-1):
f. append (f[i-1]*(p-i)/(i+1))
poly =y[0][0]
for i in range (n-1):
poly = poly +y[0][i+1]*f[i]
simp_poly = simplify(poly)
print ('\ nTHE INTERPOLATING POLYNOMIAL IS\n');
pprint(simp_poly)
# if you want to interpolate at some point the next session will help
inter = input ('Do you want to interpolate at a point (y/n)? ') # y
if inter =='y':
a= float ( input ('enter the point ')) #2
interpol = lambdify(t,simp_poly)
result = interpol(a)
print ('\ nThe value of the function at ' ,a,'is\n',result)
print("Snehashree M AI DS 4GW24AD053")

Enter number of data points : 3


Enter data for x and y:
x[0]= 1
y[0]= 2
x[1]= 3
y[1]= 4
x[2]= 4
y[2]= 6
\ nFORWARD DIFFERENCE TABLE

1.00 3.00 4.00 6.00


\ nTHE INTERPOLATING POLYNOMIAL IS

1.0⋅t + 1.0
Do you want to interpolate at a point (y/n)? 3
\ nThe value of the function at 5 is
6.0
Snehashree M AI DS 4GW24AD053

from sympy import symbols, simplify, pprint, lambdify


import numpy as np

print("This will use Newton's Backward Interpolation Formula")

# Reading number of unknowns


n = int(input('Enter number of data points: '))

# Initialize arrays for x and y values


x = np.zeros(n)
y = np.zeros((n, n))

# Reading data points


print('Enter data for x and y:')
for i in range(n):
x[i] = float(input(f'x[{i}] = '))
y[i][0] = float(input(f'y[{i}] = '))

# Generating backward difference table


for i in range(1, n):
for j in range(n - 1, i - 1, -1):
y[j][i] = y[j][i - 1] - y[j - 1][i - 1]

# Printing backward difference table


print('\nBACKWARD DIFFERENCE TABLE:\n')
for i in range(n):
print(f'{x[i]:.2f}', end='')
for j in range(i + 1):
print(f'\t{y[i][j]:.2f}', end='')
print()

# Constructing the interpolating polynomial


t = symbols('t')
h = x[1] - x[0] # Assuming equally spaced points
p = (t - x[n - 1]) / h

f = [1]
for i in range(1, n):
f.append(f[i - 1] * (p + i - 1) / i)

poly = y[n - 1][0]


for i in range(1, n):
poly += y[n - 1][i] * f[i]

simp_poly = simplify(poly)

print('\nTHE INTERPOLATING POLYNOMIAL IS:\n')


pprint(simp_poly)

# Interpolation at a specific point


inter = input('\nDo you want to interpolate at a point (y/n)? ')
if inter.lower() == 'y':
a = float(input('Enter the point: '))
interpol = lambdify(t, simp_poly)
result = interpol(a)
print(f'\nThe value of the function at {a} is:\n{result}')
print("Snehashree M AI DS 4GW24AD053")

This will use Newton's Backward Interpolation Formula


Enter number of data points: 3
Enter data for x and y:
x[0] = 4
y[0] = 4
x[1] = 5
y[1] = 6
x[2] = 4
y[2] = 4

BACKWARD DIFFERENCE TABLE:

4.00 4.00
5.00 6.00 2.00
4.00 4.00 -2.00 -4.00
THE INTERPOLATING POLYNOMIAL IS:

2
- 2.0⋅t + 12.0⋅t - 12.0

Do you want to interpolate at a point (y/n)? 3


Snehashree M AI DS 4GW24AD053

def my_func(x):
return 1 / (1 + x ** 2)

def trapezoidal(x0,xn,n):
h = (xn - x0) / n # Calculating step
# Finding sum
# Add the function value at the lower limit (x0) and the upper limit (xn)
integration = my_func(x0) + my_func(xn)
# Iterate through the sub-intervals and add 2 times the function value at each step
for i in range (1,n):
k = x0 + i * h # i-th step value
integration = integration + 2 * my_func(k) # Adding areas of the trapezoids
# Proportioning sum of trapezoid areas
integration = integration * h / 2
return integration

# Input section
lower_limit = float ( input (" Enter lower limit of integration : "))
upper_limit = float ( input (" Enter upper limit of integration : "))
sub_interval = int ( input (" Enter number of sub intervals : "))

# Call trapezoidal () method and get result


result = trapezoidal(lower_limit,upper_limit,sub_interval)

# Print result
print (" Integration result by Trapezoidal method is: " , result)
print("Snehashree M AI DS 4GW24AD053")

Enter lower limit of integration : 2


Enter upper limit of integration : 3
Enter number of sub intervals : 4
Integration result by Trapezoidal method is: 0.14241695231472232
Snehashree M AI DS 4GW24AD053

# Definition of the function to integrate


def my_func(x):
return 1 / (1 + x ** 2)

# Function to implement the Simpson 's one - third rule


def simpson13(x0,xn,n):
h = (xn - x0) / n # calculating step size

# Finding sum
integration = (my_func(x0) + my_func(xn))

# Initialize k before the loop


k = x0 + h
for i in range (1,n):
if i%2 == 0:
integration = integration + 2 * my_func(k) # Corrected coefficient for even ind
else :
integration = integration + 4 * my_func(k) # Corrected coefficient for odd indi
k += h

# Finding final integration value


integration = integration * h / 3 # Corrected divisor for Simpson's 1/3 rule
return integration

# Input section
lower_limit = float ( input (" Enter lower limit of integration : "))
upper_limit = float ( input (" Enter upper limit of integration : "))
sub_interval = int ( input (" Enter number of sub intervals : "))

# Call simpson13() method and get result


result = simpson13(lower_limit,upper_limit,sub_interval)

print (" Integration result by Simpson 's 1/3 method is: %0.6f" % ( result))
print("Snehashree M AI DS 4GW24AD053")

Enter lower limit of integration : 3


Enter upper limit of integration : 4
Enter number of sub intervals : 5
Integration result by Simpson 's 1/3 method is: 0.072667
Snehashree M AI DS 4GW24AD053

def simpsons_3_8_rule(func, a, b, n):


h = (b - a) / n
# Use the renamed function 'func'
s = func(a) + func(b) # Correctly using the 'func' parameter here
for i in range(1, n, 3):
s += 3 * func(a + i * h)
for i in range(3, n - 1, 3):
s += 3 * func(a + i * h)
for i in range(2, n - 2, 3):
s += 2 * func(a + i * h)
return s * 3 * h / 8

# Renamed the local function f to my_integration_func to avoid conflict


def my_integration_func(x):
return 1 / (1 + x ** 2) # function here

a = 0 # lower limit
b = 6 # upper limit
n = 6 # number of sub intervals

# Call simpsons_3_8_rule with the renamed function


result = simpsons_3_8_rule(my_integration_func, a, b, n)
print('%3.5f ' % result)
print("Snehashree M AI DS 4GW24AD053")

1.27631
Snehashree M AI DS 4GW24AD053

from numpy import array, zeros, exp


def taylor(deriv, x, y, xStop, h):
X = []
Y = []
X.append(x)
Y.append(y[0])
while x < xStop: # Loop over integration steps
D = deriv(x, y)
H = 1.0
for j in range(3): # Build Taylor series (up to 3rd order)
H = H * h / (j + 1) # h^j / j!
y[0] = y[0] + D[j][0] * H
x = x + h
X.append(x)
Y.append(y[0])
return array(X), array(Y)

def deriv(x, y):


D = zeros((4, 1))
D[0][0] = 2 * y[0] + 3 * exp(x) # y'
D[1][0] = 4 * y[0] + 9 * exp(x) # y''
D[2][0] = 8 * y[0] + 21 * exp(x) # y'''
D[3][0] = 16 * y[0] + 45 * exp(x) # y(4)
return D

# Initial values
x = 0.0
xStop = 0.3
y = array([0.0])
h = 0.1

# Compute using Taylor series method


X, Y = taylor(deriv, x, y, xStop, h)

# Print results
print("The required values are:")
for i in range(len(X)):
print(f"x = {X[i]:.2f}, y = {Y[i]:.5f}")
print("Snehashree M AI DS 4GW24AD053")

The required values are:


x = 0.00, y = 0.00000
x = 0.10, y = 0.34850
x = 0.20, y = 0.81079
x = 0.30, y = 1.41590
Snehashree M AI DS 4GW24AD053

import numpy as np
import matplotlib.pyplot as plt
# Define parameters
f = lambda x,y: np.exp(-x) # ODE
h = 0.2 # Step size
y0 = -1 # Initial Condition
n=3
# Explicit Euler Method
# Initialize x as a NumPy array of size n+1
x = np.zeros(n+1)
# Initialize y as a NumPy array of size n+1
y = np.zeros(n+1)
y[0] = y0
x[0]=0
for i in range (0,n):
x[i+1]=x[i]+h
y[i + 1] = y[i] + h*f(x[i], y[i]) # This line was causing an IndentationError in the orig

print ("The required values are at x= %0.2f , y=%0.5f , x=%0.2f , y=%0.5f ,x = %0.2f , y=%0
print ("\n\n")
# Corrected the format strings for plt.plot
plt. plot (x,y, 'bo--', label =' Approximate ')
plt. plot (x, -np.exp (-x), 'g*-', label ='Exact ')
plt.title(" Approximate and Exact Solution " )
plt. xlabel ('x')
plt. ylabel ('f(x)')
plt. grid ()
# Removed the trailing space from 'best '
plt. legend (loc ='best')
plt.show()
print("Snehashree M AI DS 4GW24AD053")

The required values are at x= 0.00 , y=-1.00000 , x=0.20 , y=-0.80000 ,x = 0.40

import numpy as np
import matplotlib.pyplot as plt

# Corrected Modified Euler function definition


def modified_euler(f, x0, y0, h, n):
# Initialize x and y arrays inside the function body
x = np.zeros(n+1)
y = np.zeros(n+1)
x[0] = x0
y[0] = y0
for i in range(n):
x[i + 1] = x[i] + h
k1 = h * f(x[i], y[i])
k2 = h * f(x[i + 1], y[i] + k1)
y[i + 1] = y[i] + 0.5 * (k1 + k2)
return x, y

# Define the ODE function


def f(x, y):
return -0.01 * y # ODE dy/dx = -ky

# Input parameters
x0 = 0.0
y0 = 100.0
h = 25
n = 4

# Call the modified_euler function and get the results


x, y = modified_euler(f, x0, y0, h, n)

# Print the result at the last point


print("The required value at x= %0.2f , y=%0.5f" % (x[4], y[4]))
print("\n\n")

# Plotting the results


plt.plot(x, y, 'bo-')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Solution of dy/dx = -ky using Modified Euler\'s Method')
plt.grid(True)
plt.show()
print("Snehashree M AI DS 4GW24AD053")

The required value at x= 100.00 , y=37.25290

from sympy import *


import numpy as np

def RungeKutta(g, x0, h, y0, xn):


# Change symbol names to avoid conflict with global numpy arrays
# Use 'x' and 'y' as symbols to match the expression string
x_sym, y_sym = symbols('x,y')
# Lambdify the expression with respect to x and y
f = lambdify([x_sym, y_sym], g)
xt = x0 + h
Y = [y0]
current_x = x0 # Use different variable names for the numerical values
current_y = y0

while current_x < xn: # Use current_x for the loop condition
k1 = h * f(current_x, current_y)
k2 = h * f(current_x + h / 2, current_y + k1 / 2)
k3 = h * f(current_x + h / 2, current_y + k2 / 2)
k4 = h * f(current_x + h, current_y + k3)
y1 = current_y + (1 / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
Y.append(y1)
# print ('y(%3.3f '%xt ,') is %3.3f '%y1)
current_x += h # Update current numerical values by adding h
current_y = y1
# Update xt as well for potential logging/printing, though current_x is used for the
xt = current_x

return np.round(Y, 2)

# The ODE string should now match the symbol names used in lambdify ('x' and 'y')
result = RungeKutta('1+(y/x)', 1, 0.2, 2, 2)
print(result) # Print the returned result
print("Snehashree M AI DS 4GW24AD053")

[2. 2.62 3.27 3.95 4.66 5.39 6.13]


Snehashree M AI DS 4GW24AD053

x0=1
y0=2
y1=2.2156
y2=2.4649
y3=2.7514
h=0.1
x1=x0+h
x2=x1+h
x3=x2+h
x4=x3+h
def f(x y):

You might also like