0% found this document useful (0 votes)
52 views

Computer Assignment

The document contains code for several numerical methods: 1) Bisection method to find the root of a function between 0 and 1. 2) Newton Raphson method to iteratively find the root of a function starting from an initial guess. 3) Cubic interpolation to fit a cubic spline to sinusoidal data. 4) LU decomposition to solve a system of linear equations. 5) Numerical integration using trapezoidal, Simpson's 1/3, and Simpson's 3/8 rules. 6) Numerical differentiation using forward, backward, and central difference methods.

Uploaded by

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

Computer Assignment

The document contains code for several numerical methods: 1) Bisection method to find the root of a function between 0 and 1. 2) Newton Raphson method to iteratively find the root of a function starting from an initial guess. 3) Cubic interpolation to fit a cubic spline to sinusoidal data. 4) LU decomposition to solve a system of linear equations. 5) Numerical integration using trapezoidal, Simpson's 1/3, and Simpson's 3/8 rules. 6) Numerical differentiation using forward, backward, and central difference methods.

Uploaded by

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

ASSIGNMENT 1

ROHIT NILKANTH CHAUDHARI

J18INT640

20/7/2019

BISECTION METHOD
import numpy as np
import matplotlib.pyplot as plt
import math
def f(x):
return (x**3)-(5*x)+1
def bisection(a,b,tol):
xl=a
xr=b
while(np.abs(xl-xr)>tol):
c=(xl+xr)/2
prod=f(xl)*f(c)
if prod>tol:
xl=c
else:
xr=c
return c
answer= bisection(0,1,0.0005)
print("bisection method gives root at x=",answer)

x= np.linspace(-10,10,1000)
y=f(x)
plt.plot(x,y)
plt.grid()
plt.title("Plot of Equation")
plt.xlabel("X")
plt.ylabel("F(x)")
plt.legend(["x"])

OUTPUT

bisection method gives root at x= 0.19775390625


<matplotlib.legend.Legend at 0xea72c79cf8>

NEWTON RAPHSON METHOD


import numpy as np
from scipy.misc import derivative
import matplotlib.pyplot as plt

x_n = 5.5
y= np.pi
print(y)
x = np.linspace(y, y/2, 500)
def f(x):
return x**2-5*x+(x/2)
def x_next(f, x, x_n):
slope= derivative(f, x_n, dx= 0.1)
return x_n-f(x_n)/slope
for n in range(10):
#print(x_n)
print("x_iteration_{}={}".format(n+1,x_n))
x_n = x_next(f, x, x_n)
y=f(x)
plt.plot(x,y,color = "g")
plt.grid()

OUTPUT
3.141592653589793
x_iteration_1=5.5
x_iteration_2=4.653846153846149
x_iteration_3=4.504923076923077
x_iteration_4=4.5000053741714385
x_iteration_5=4.500000000006418
x_iteration_6=4.499999999999999
x_iteration_7=4.5
x_iteration_8=4.5
x_iteration_9=4.5
x_iteration_10=4.5
CUBIC INTERPOLATION
import numpy as np
from scipy.interpolate import CubicSpline
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.sin(x)
cs = CubicSpline(x,y)
xs = np.arange(-0.5,9.6,0.1)
plt.figure(figsize = (6.5,4))
plt.plot(x,y,'o',label = 'data')
plt.plot(xs,np.sin(xs),label = 'true')
plt.plot(xs,cs(xs,1),label = "s")
plt.plot(xs,cs(xs,2),label = "s'")
plt.plot(xs,cs(xs,3),label = "s'''")
plt.xlim(-0.5,9.5)
plt.legend(loc='lower left',ncol=2)
plt.show()

OUTPUT

LU DECOMPOSITION
import numpy as np
import pprint
import scipy.linalg
from scipy.linalg import lu_factor,lu_solve

A = scipy.array([[7,5,-1,2],[3,8,1,-4],[-1,1,4,-1],[2,-4,-1,6]])
print(A)
b = np.array([1,1,1,1])
print(b)
P,L,U = scipy.linalg.lu(A)
print("A")
pprint.pprint(A)
print("P:")
pprint.pprint(P)
lu,piv = lu_factor(A)
x = lu_solve((lu,piv),b)
print(x)

OUTPUT
[[ 7 5 -1 2]
[ 3 8 1 -4]
[-1 1 4 -1]
[ 2 -4 -1 6]]
[1 1 1 1]
A
array([[ 7, 5, -1, 2],
[ 3, 8, 1, -4],
[-1, 1, 4, -1],
[ 2, -4, -1, 6]])
P:
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
[-1.09734513 1.20353982 0.00884956 1.33628319]

INTERPOLATE
import numpy as np
from scipy import interpolate
import pylab as py
x = np.linspace(0, 10, 11)
y = np.cos(x)
xnew = np.linspace(0, 10, 100)
py.figure(1)
py.plot('o')
for kind in ['linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic']:
f = interpolate.interp1d(x,y, kind = kind)
ynew = f(xnew)
plt.plot(xnew, ynew, label = kind)
plt.legend(loc = 'best')

OUTPUT
TAYLORS SERIES EXPANSION
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
x = np.linspace( 0, 0.5, 10 )
f = 1.0 / (1 - x)
f0 = 1 + np.zeros(10)
f1 = 1 + x
f2 = 1 + x + x**2
plt.figure()
plt.plot(x, f, "k", label = " $f = 1/ (1-x)$")
plt.errorbar(x, f, yerr = 0.00005, fmt = "d")
plt.plot(x, f0, "r", label = " $f - 1$")
plt.plot(x, f1, "g", label = " $f - 1 + x$")
plt.plot(x, f2, "--", label = " $f - 1 + x + x**2$")
plt.grid("on")
plt.legend()
OUTPUT

TRAPAZOIDAL RULE
from math import sin,pi
f=lambda x:x*sin(x)
a=0
b=pi/2
n=90
h=(b-a)/n

s= 0.5*(f(a) + f(b))

for i in range(1,n):
s+=f(a+i*h)
integral = h*s
print(integral)

OUTPUT
1.0000253851716194
SIMPSONS 1/3 RULE
from math import sin,pi
f=lambda x:x*sin(x)
a=0
b=pi/2
n=90
h=((b-a)/n)
s=(f(a) + f(b))/3

for i in range(1,n,2):
s+=(4*f(a+i*h))/3

for i in range(2,n,2):
s+=(2*f(a+i*h))/3

integral = h*s
print(integral)

from math import sin, pi


f = lambda x : x * sin(x)
a=0
b = pi/2
n = 90
h = (b - a) / n
s = ( f(a) + f(b))/3
for i in range( 1, n, 2 ):
s+= (4*f(a + i*h))/3
for i in range(2, n, 2):
s+= (2*f( a + i*h))/3
integral1 = h * s
print(integral1)

error1 = (( integral - integral1 )/(integral)) * 100


print ("error1 = ", error1, "%")

OUTPUT

0.999999998453377
0.999999998453377
error1 = 0.0 %

SIMPSONS 3/8 RULE


from math import sin, pi
f = lambda x : x * sin(x)
a=0
b = pi/2
n = 90
h = (b - a) / n
s = ( f(a) + f(b) )*(3/8)
for i in range( 1, n, 3 ):
s+= (3*f(a + i*h))*(3/8)
for i in range(3, n, 3):
s+= (2*f( a + i*h))*(3/8)
for i in range(2, n, 3):
s+= (3*f( a + i*h))*(3/8)
integral2 = h * s
print(integral2)
error2 = 100 - (( integral2 )/(integral) * 100)
print ("error2 = ", error2, "%")

OUTPUT

0.9999999965198877
error2 = 0.0025388007252757916 %

NUMERICAL DIFFERENTIATION
import numpy as np
def derivatives(f, a, method = "central", h = 0.01):
if method == "central":
return (f(a + h) - f(a - h)) / (2 * h)
elif method == "forward":
return (f(a + h) - f(a)) / (h)
elif method == "backward":
return (f(a) - f(a - h)) / (h)
else:
return ValueError("method must be central, forward or backward")
derivatives( np.cos, 0)
derivatives( np.cos, 0, method = "forward")
derivatives( np.cos, 0, method = "backward", h = 0.0005)

OUTPUT
0.000249999994705874

import numpy as np
from scipy.misc import derivative
x = np.linspace( 0, 5*np.pi, 100 )
dydx = derivative(np.sin, x)
module = derivative( np.sin, x, dx = 0.1 )
dYdx = np.cos(x)
dydx
from matplotlib import pyplot as plt
plt.figure(figsize=(15,5))
plt.plot(x,dydx,"y",label="central difference", marker="D")

OUTPUT

You might also like