Bisection Method
Program :
from math import fabs
def fun(x):
return x*x*x-4*x-9
def bisection(a,b,e):
c=(a+b)/2
fc=fun(c)
print(f"{'iter'}\t{'a'}\t{'b'}\t{'c'}\t{'fc'}")
print('.'*100)
count=1
while fabs(fc)>e:
c=(a+b)/2
fc=fun(c)
print(f"{count}\t{round(a,5)}\t{round(b,5)}\t{round(c,5)}\
t{round(fc,5)}")
fa=fun(a)
fb=fun(b)
if (fa*fc<0):
b=c
else:
a=c
count=count+1
e=0.00001
a=2
b=3
fa=fun(a)
fb=fun(b)
if(fa*fb>0):
print("Invalid Guess")
else:
bisection(a,b,e)
iter a b c fc
.............................................................................
.......................
1 2 3 2.5 -3.375
2 2.5 3 2.75 0.79688
3 2.5 2.75 2.625 -1.41211
4 2.625 2.75 2.6875 -0.33911
5 2.6875 2.75 2.71875 0.22092
6 2.6875 2.71875 2.70312 -0.06108
7 2.70312 2.71875 2.71094 0.07942
8 2.70312 2.71094 2.70703 0.00905
9 2.70312 2.70703 2.70508 -0.02604
10 2.70508 2.70703 2.70605 -0.00851
11 2.70605 2.70703 2.70654 0.00027
12 2.70605 2.70654 2.7063 -0.00412
13 2.7063 2.70654 2.70642 -0.00192
14 2.70642 2.70654 2.70648 -0.00083
15 2.70648 2.70654 2.70651 -0.00028
16 2.70651 2.70654 2.70653 -0.0
Secant Method:
Program :
from math import fabs
def f(x):
return x**3 - 2*x - 5
def secant(a, b, e):
print(f"{'iter'} \t {'a'} \t {'b'} \t {'c'} \t")
print("."*50)
count = 0
while fabs(f(b)) > e:
fa = f(a)
fb = f(b)
c = (a * fb - b * fa) / (fb - fa)
print(f"{count} \t {a:.4f} \t {b:.4f} \t {c:.4f} \t")
a, b = b, c
count += 1
print(f"The solution of given problem is {b:.4f}")
e = 0.0001
a = float(input("Enter First Guess: "))
b = float(input("Enter Second Guess: "))
if f(a) * f(b) > 0:
print("Invalid guesses: f(a) and f(b) must have opposite signs.")
else:
secant(a, b, e)
Enter First Guess: 2
Enter Second Guess: 3
iter a b c
..................................................
0 2.0000 3.0000 2.0588
1 3.0000 2.0588 2.0813
2 2.0588 2.0813 2.0948
3 2.0813 2.0948 2.0945
The solution of given problem is 2.0945
Newton Rapson Method:
Program :
from math import fabs
def f(x):
return x**2 - 5*x +6
def df(x):
return 2*x - 5
def nr(a, e):
print(f"{'iter'} \t {'x'} \t {'b'}")
print("."*30)
count = 0
while fabs(f(a)) > e:
fx = f(a)
dfx = df(a)
b = a - fx / dfx
print(f"{count} \t {a:.4f} \t {b:.4f}")
a= b
count += 1
print(f"The solution of the given problem is {a:.4f}")
e = 0.000001
a = float(input("Enter Initial Guess: "))
nr(a, e)
Enter Initial Guess: 2.4
iter x b
..............................
0 2.4000 1.2000
1 1.2000 1.7538
2 1.7538 1.9594
3 1.9594 1.9985
4 1.9985 2.0000
5 2.0000 2.0000
The solution of the given problem is 2.0000