-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNM - bisectionmethod.py
More file actions
34 lines (34 loc) · 1001 Bytes
/
NM - bisectionmethod.py
File metadata and controls
34 lines (34 loc) · 1001 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from math import *
thefun = input("Enter function on x : ")
def f(x):
return eval(thefun)
def bijection(a, b):
return (a+b)/2
a, b=int(input('Enter value for a : ')), int(input('Enter value for b : '))
if f(a)<0:#negative fa
while f(b)<0: #negative fb
if f(b)-f(a)>0:
a, b=b, b+b-a
else:
a, b=a, b-2*(b-a)
else:#positive fa
while f(b)>0: #positive fb
if f(b)-f(a)>0:
a,b=a,b-2*(b-a)
else :
a, b=b, b+b-a
a, b=min(a, b), max(a, b)
x=bijection(a, b)
accuracy=3
w=0
n=1
print("Root lies between {} and {}".format(a, b))
print("n\ta\tf(a)\tb\tf(b)\txn\tf(xn)\n")
while (round(w, accuracy)!=round(x, accuracy)):
w=x
print(n, round(a, accuracy), round(f(a), accuracy), round(b, accuracy), round(f(b), accuracy),round(x, accuracy), round(f(x), accuracy), sep='\t')
if (f(a)>0) == (f(x)>0):a=x
else:b=x
n+=1
x=bijection(a, b)
input("Press enter to quit")