2024 Week 10 Roots - Jupyter Notebook
2024 Week 10 Roots - Jupyter Notebook
Bisection
𝑥𝑛+1 = 𝑥𝑛 +2𝑥𝑛−1
In [2]: 1 def bisection_method(f, a, b, tolerance, N=100):
2 x = np.zeros(N)
3 x[0] = a
4 x[1] = b
5 for i in range(2,N):
6 mid = (x[i-2] + x[i-1])/2
7 if (abs(mid-x[i-1]) < tolerance):
8 x[i] = mid
9 break
10 if f(x[i-2])*f(mid) > 0:
11 x[i] = mid
12 else:
13 x[i-1] = x[i-2]; x[i] = mid
14 return (i, x[i])
15
16 def f(x):
17 return x**3 + 3*x**2 + 6*x + 9
18
19 a = -5
20 b = 5
21 tolerance = 1e-4
22 N = 10
23 root = bisection_method(f, a, b, tolerance, N)[1]
24 round(root, 2)
Out[2]: -2.15
Newton-Raphson
Out[3]: (1.7918, 5)
Write a python program to find the root of the equation sin(𝑥) = 𝑥, using relaxation method.
Take the initial guess to be𝑥=1 𝑒𝑝𝑠 = 10−4 𝑁 = 1000
, tolerance to be and iterations. What is the value of the root rounded to 3 decimal places?.
𝑥
Hint : define array with size𝑁 and store𝑥[0] = 1 .
1 𝑁
Now enter a for loop from to 𝑥[𝑖] = 𝑓(𝑥[𝑖 − 1])
and calculate 𝑎𝑏𝑠(𝑥[𝑖] − 𝑥[𝑖 − 1]) < 𝑒𝑝𝑠
until the ,
when that happens break out of the loop and store the answer as 𝑎𝑛𝑠 = 𝑥[𝑖] .
Note: The value of 𝑁 is only given so that program does not go into infinite loop.
You will get the answer within given tolerance much earlier than loop completes.
Out[4]: 0.084
Write a python program to find the root of 𝑓(𝑥) = 𝑒𝑥𝑝(𝑥) − 6, using secant method.
𝑥0 = 3, 𝑥1 = 2.5,𝑒𝑝𝑠 = 10−4 and 𝑁 = 10 iterations.
Take the two initial points to be
𝑎
Let be the value of the root by the secant method.
Now you solved the same equation with newton-raphson method with initial value 3.0 , tolerance 10 and 10 iterations in question 4.
−4
Let 𝑏 be the answer by newton-raphson method (the complete answer not the rounded one).
Now define 𝑒 = 𝑏 ∗ 10 , What is the value of 𝑒 rounded to 4 decimal places?
𝑎−𝑏 5
Note: for secant method the loop will start from 𝑖 = 2 to 𝑁 . Since 𝑥[0] = 3.0 and 𝑥[1] = 2.5 are already given.
You should have a tolerance condition 𝑎𝑏𝑠(𝑥[𝑖] − 𝑥[𝑖 − 1]) < 𝑒𝑝𝑠 , after calculating successive value of 𝑥 so that
you can break out of the for loop if the tolerance condition is met.
When the condition is met break out of loop and store the answer as 𝑎𝑛𝑠 = 𝑥[𝑖] where 𝑖 is the loop index at which the for loop breaks.
Secant
Out[5]: 0.2572
Write a python program to find the roots of the equation 𝑓(𝑥) = 𝑠𝑖𝑛(𝑥) using bisection method. Take 𝑁 = 100 𝑒𝑝𝑠 = 10−4
, and .
𝑥
You have to find two roots, one negative and one positive. For the negative root take0 = −5, 𝑥 1 = 0
. For the positive root take𝑥0 = 1, 𝑥1 = 5.
Let 𝑟𝑝 be the positive root and 𝑟𝑛 be the negative root. Now define 𝑒 = 𝑟𝑛−𝑟𝑝 × 10 , What is the value of 𝑒 to 4 decimal places?
𝑟𝑛+𝑟𝑝 6
𝑓(𝑥) = 𝑥2 − 1 , using the brentq function from scipy.optimize module. Take the interval to be
Write a python program to find the root of the function
[0.5,1.5] .
Let the value of root be 𝑟 . Now define 𝑒 = 𝑟 ∗ 10 , What is the value of 𝑒 rounded to three decimal places?
1−𝑟 15
Out[7]: 0.666
Out[8]: 4.4964