Computer Assignment
Computer Assignment
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
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)
OUTPUT
0.999999998453377
0.999999998453377
error1 = 0.0 %
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