Lab - Session - 1.ipynb - Colaboratory

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Lab Task 1: Plot all the given functions to observe the roots by visualization, fill the table by your

visual guess of root. We have plotted one


function for you.
1) f (x) = cos(x) − 1.3x

2) f (x) = xcos(x) − 2x
2
+ 3x − 1

3) f (x) = 2xcos(2x) − (x + 1)
2

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 7.50]

def f(x):
return (np.cos(x)-1.3*x)

x = np.linspace(-10,10 , 1000)
plt.plot(x,f(x), color='red')
plt.hlines(y=0,xmin=-10,xmax=10,color='blue')
plt.show()

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 7.50]

def f(x):
return (x*np.cos(x)-2*(x**2)+3*x-1)

x = np.linspace(-10,10 , 1000)
plt.plot(x,f(x), color='red')
plt.hlines(y=0,xmin=-10,xmax=10,color='blue')
plt.show()
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 7.50]

def f(x):
return (2*x*np.cos(2*x)-(x+1)**2)

x = np.linspace(-10,10 , 1000)
plt.plot(x,f(x), color='red')
plt.hlines(y=0,xmin=-10,xmax=10,color='blue')
plt.show()
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [10, 10] # Increased figure size

def f(x):
return (np.cos(x) - 1.3 * x)

x = np.linspace(-10, 10, 1000)


plt.plot(x, f(x), color='red')

# Adding space around the plot


plt.xlim(-2, 2)
plt.ylim(-5, 5)

plt.hlines(y=0, xmin=-10, xmax=10, color='blue')


plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Plot of the function f(x)')

plt.show()
Lab Task 2: Complete the missing code of bisection method accordding to the explained algorithm and find root of given problems by bisection
method according to the instructions given in table.
1) f 1(x) = cos(x) − 1.3x

2) f 2(x) = xcos(x) − 2x
2
+ 3x − 1

3) f 3(x) = 2xcos(2x) − (x + 1)
2

import numpy as np
from tabulate import tabulate

def func(x):
return (2*x*np.cos(2*x)-(x+1)**2)

def bisection(func, x1, x2, tol=0.00001, max_iter=100):


if func(x1) * func(x2) >= 0:
return "Error: Choose different interval, function should have different signs at the interval endpoints."
data=[]
iter = 0
xr = x2
error = tol + 1
while iter < max_iter and error > tol:
xrold = xr
xr = ((x1+x2)/2)
iter += 1
error = abs((xr - xrold) )

test = func(x1) * func(xr)


# write your code here to replace value of x1 or x2 by xr
data.append([iter+1,x1,func(x1),x2,func(x2),xr,func(xr),error])
if test < 0:
x2 = xr
elif test > 0:
x1 = xr
else:
error = 0

print(tabulate(data,headers=['#','x1','f(x1)','x2','f(x2)','xr','f(xr)',"error"],tablefmt="github"))
print('\nRoot of given function is x=%.9f in n=%d number of iterations with a tolerence=%.4f' %(xr,iter,tol))

return
bisection(func,-5,-1)

| # | x1 | f(x1) | x2 | f(x2) | xr | f(xr) | error |


|-----|----------|--------------|----------|-------------|----------|--------------|-------------|
| 2 | -5 | -7.60928 | -1 | 0.832294 | -3 | -9.76102 | 2 |
| 3 | -3 | -9.76102 | -1 | 0.832294 | -2 | 1.61457 | 1 |
| 4 | -3 | -9.76102 | -2 | 1.61457 | -2.5 | -3.66831 | 0.5 |
| 5 | -2.5 | -3.66831 | -2 | 1.61457 | -2.25 | -0.613919 | 0.25 |
| 6 | -2.25 | -0.613919 | -2 | 1.61457 | -2.125 | 0.630247 | 0.125 |
| 7 | -2.25 | -0.613919 | -2.125 | 0.630247 | -2.1875 | 0.0380755 | 0.0625 |
| 8 | -2.25 | -0.613919 | -2.1875 | 0.0380755 | -2.21875 | -0.280836 | 0.03125 |
| 9 | -2.21875 | -0.280836 | -2.1875 | 0.0380755 | -2.20312 | -0.119557 | 0.015625 |
| 10 | -2.20312 | -0.119557 | -2.1875 | 0.0380755 | -2.19531 | -0.0402785 | 0.0078125 |
| 11 | -2.19531 | -0.0402785 | -2.1875 | 0.0380755 | -2.19141 | -0.000985195 | 0.00390625 |
| 12 | -2.19141 | -0.000985195 | -2.1875 | 0.0380755 | -2.18945 | 0.0185743 | 0.00195312 |
| 13 | -2.19141 | -0.000985195 | -2.18945 | 0.0185743 | -2.19043 | 0.00880185 | 0.000976562 |
| 14 | -2.19141 | -0.000985195 | -2.19043 | 0.00880185 | -2.19092 | 0.00391015 | 0.000488281 |
| 15 | -2.19141 | -0.000985195 | -2.19092 | 0.00391015 | -2.19116 | 0.00146293 | 0.000244141 |
| 16 | -2.19141 | -0.000985195 | -2.19116 | 0.00146293 | -2.19128 | 0.000238981 | 0.00012207 |
| 17 | -2.19141 | -0.000985195 | -2.19128 | 0.000238981 | -2.19135 | -0.000373078 | 6.10352e-05 |
| 18 | -2.19135 | -0.000373078 | -2.19128 | 0.000238981 | -2.19131 | -6.70414e-05 | 3.05176e-05 |
| 19 | -2.19131 | -6.70414e-05 | -2.19128 | 0.000238981 | -2.1913 | 8.59717e-05 | 1.52588e-05 |
| 20 | -2.19131 | -6.70414e-05 | -2.1913 | 8.59717e-05 | -2.19131 | 9.46558e-06 | 7.62939e-06 |

Root of given function is x=-2.191307068 in n=19 number of iterations with a tolerence=0.0000

Lab Task 3: Find root of given problems by Newton Raphson method according to the instructions given in table.
1) f 1(x) = cos(x) − 1.3x

2) f 2(x) = xcos(x) − 2x
2
+ 3x − 1

3) f 3(x) = 2xcos(2x) − (x + 1)
2

import numpy as np
from tabulate import tabulate

## module Newton_Raphson
''' newton_raphson(func, dfunc, x0, tol=1e-4, max_iter=1000)
Finds a root of f(x) = 0 by newton_raphson.
'''
def func(x):
return (2*x*np.cos(2*x)-(x+1)**2)
def dfunc(x):
return ( 2*np.cos(2*x)- 4*x*np.sin(2*x) - 2*(x+1))
def newton_raphson(func, dfunc, x0, tol=0.001, max_iter=1000):
xr = x0
data=[]
iter = 0
error = tol + 1
for i in range(max_iter):
iter+=1
fx = func(xr)
dx = dfunc(xr)
if abs(dx) < tol:
raise Exception("Derivative is close to zero!")
xrold=xr
xr = xr - fx/dx
error=abs(xr-xrold)
data.append([iter,xr,func(xr),error])
if error < tol:
print(tabulate(data,headers=['Iteration','xr','f(xr)',"error"],tablefmt="github"))
print('\nRoot of given function is x=%.9f in n=%d number of iterations with a tolerence=%.4f' %(xr,iter,tol))
return

raise Exception("Max iterations reached")


newton_raphson(func,dfunc, -10)
| Iteration | xr | f(xr) | error |
|-------------|--------------|-----------------|--------------|
| 1 | -15.0369 | -203.853 | 5.03691 |
| 2 | -12.6967 | -161.348 | 2.34021 |
| 3 | 0.488766 | -1.66991 | 13.1855 |
| 4 | 0.00895666 | -1.00008 | 0.479809 |
| 5 | -52.9729 | -2769.64 | 52.9819 |
| 6 | -42.598 | -1651.06 | 10.3749 |
| 7 | -31.0868 | -954.402 | 11.5112 |
| 8 | -24.1618 | -518.941 | 6.92506 |
| 9 | -20.3366 | -333.8 | 3.82518 |
| 10 | -5.90972 | -32.7781 | 14.4269 |
| 11 | -4.71112 | -4.35021 | 1.1986 |
| 12 | -3.9017 | -8.8144 | 0.809421 |
| 13 | -4.81206 | -5.09827 | 0.91036 |
| 14 | -4.274 | -5.25147 | 0.538055 |
| 15 | -4.94106 | -6.6655 | 0.66706 |
| 16 | -4.49115 | -4.07088 | 0.449914 |
| 17 | -6.10841 | -37.574 | 1.61726 |
| 18 | -4.27228 | -5.26509 | 1.83614 |
| 19 | -4.93849 | -6.62745 | 0.666209 |
| 20 | -4.48793 | -4.07916 | 0.450561 |
| 21 | -6.04666 | -36.2341 | 1.55874 |
| 22 | -4.46391 | -4.15078 | 1.58275 |
| 23 | -5.70558 | -26.7495 | 1.24167 |
| 24 | -4.84542 | -5.43741 | 0.860159 |
| 25 | -4.34462 | -4.74369 | 0.500804 |
| 26 | -5.07956 | -9.10206 | 0.734946 |
| 27 | -4.63096 | -4.04452 | 0.448599 |
| 28 | -2.86103 | -8.30801 | 1.76994 |
| 29 | -2.13892 | 0.50381 | 0.722103 |
| 30 | -2.19371 | -0.0240944 | 0.0547834 |
| 31 | -2.19131 | -4.3573e-05 | 0.00239403 |
| 32 | -2.19131 | -1.43924e-10 | 4.34515e-06 |

Root of given function is x=-2.191308012 in n=32 number of iterations with a tolerence=0.0010

Lab Task 4: Find root of given problems by using fsolve command of scipy.optimize
1) f 1(x) = cos(x) − 1.3x

2) f 2(x) = xcos(x) − 2x
2
+ 3x − 1

3) f 3(x) = 2xcos(2x) − (x + 1)
2

import scipy.optimize
dir(scipy.optimize)
'minimize_scalar',
'minpack',
'minpack2',
'moduleTNC',
'newton',
'newton_krylov',
'nnls',
'nonlin',
'optimize',
'quadratic_assignment',
'ridder',
'root',
'root_scalar',
'rosen',
'rosen_der',
'rosen_hess',
'rosen_hess_prod',
'shgo',
'show_options',
'slsqp',
'test',
'tnc',
'toms748',
'zeros']

import scipy.optimize as opt


import numpy as np
equation=lambda x: np.cos(x)-1.3*x
print(opt.fsolve(equation,0))
equation=lambda x: x*np.cos(x)-2*(x**2)+3*x-1
print(opt.fsolve(equation,0))
equation=lambda x: 2*x*np.cos(2*x)-(x+1)**2
print(opt.fsolve(equation,-2))

[0.62418458]
[0.29753023]
[-2.19130801]

Lab Task 5: Write program of Secant and False Position method by altering above codes.

#Lab Task 5 Secant Method

import numpy as np
from tabulate import tabulate
def func(x):
return (2*x*np.cos(2*x)-(x+1)**2)
def secant(func, x0, x1, tol=0.001, max_iter=1000):
if func(x1) * func(x0) >= 0:
return "Error: Choose different interval, function should have different signs at the interval endpoints."
iter= 0
error=tol+1
xr=x1
xrold=x0
data=[]
while iter < max_iter and error > tol:
data.append([iter,xr,func(xr),xrold,func(xrold),error])
xrold=xr
xr=xr-(func(xr)*(xr-x0))/(func(xr)-func(x0))
x0=xrold
iter+=1
error=abs(func(xr)-func(xrold))
print(tabulate(data,headers=['Iteration','xr','f(xr)', 'xrold' ,'f(xrold)',"error"],tablefmt="github"))
print('\nRoot of given function is x=%.9f in n=%d number of iterations with a tolerence=%.5f' %(xr,iter,tol))
secant(func,-3,-2)

| Iteration | xr | f(xr) | xrold | f(xrold) | error |


|-------------|----------|--------------|----------|-------------|------------|
| 0 | -2 | 1.61457 | -3 | -9.76102 | 1.001 |
| 1 | -2.14193 | 0.476053 | -2 | 1.61457 | 1.13852 |
| 2 | -2.20128 | -0.100752 | -2.14193 | 0.476053 | 0.576805 |
| 3 | -2.19091 | 0.00395237 | -2.20128 | -0.100752 | 0.104704 |
| 4 | -2.19131 | 2.95946e-05 | -2.19091 | 0.00395237 | 0.00392278 |

Root of given function is x=-2.191308013 in n=5 number of iterations with a tolerence=0.00100

#Lab Task 5 False Position Method code

import numpy as np
p py p
from tabulate import tabulate
def func(x):
return (2*x*np.cos(2*x)-(x+1)**2)
def false_position(func, x0, x1, tol=0.00001, max_iter=1000):
if func(x1) * func(x0) >= 0:
return "Error: Choose different interval, function should have different signs at the interval endpoints."
iter= 0
error=tol+1
if x0<0:
a=x0
b=x1
else:

You might also like