-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroot_finder.py
45 lines (35 loc) · 1.05 KB
/
root_finder.py
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
35
36
37
38
39
40
41
42
43
44
45
from polynominal import parse_poly
EPS = 1e-5
def same_sign(a, b):
return a * b > 0
def find_root(poly, a, b):
if not a or not b:
return ''
a, b = float(a), float(b)
if same_sign(poly.evaluate(a), poly.evaluate(b)):
return 'No confirmed root between {} and {}'.format(a, b)
while a - b > EPS:
y_a, y_b = poly.evaluate(a), poly.evaluate(b)
middle = (a + b) / 2
y_middle = poly.evaluate(middle)
if y_a == 0:
return a
elif y_b == 0:
return b
elif y_middle == 0:
return middle
if same_sign(y_middle, y_a):
a = middle
else:
b = middle
return round(a, 5)
if __name__ == '__main__':
poly = parse_poly(input('Enter a polynominal: '))
print('You entered a polynominal: {}'.format(poly))
print('Finding roots to precision of 5 decimal places')
a = b = 1
while a and b:
print('Find a root between...')
a = input('a: ')
b = input('b: ')
print(find_root(poly, a, b))