-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroot-approximator.py
More file actions
40 lines (34 loc) · 811 Bytes
/
Copy pathroot-approximator.py
File metadata and controls
40 lines (34 loc) · 811 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
35
36
37
38
39
40
from math import *
expr = input("Enter a function:\n")
a = float(input("[!] Enter first segment bound: "))
b = float(input("[!] Enter second segment bound: "))
x1 = a
x2 = b
x3 = x2
exact = None
i = 0
while i <= 100:
f1 = eval(expr.replace("x", "x1"))
f2 = eval(expr.replace("x", "x2"))
if (f1 * f2) < 0:
x3 = x2
x2 = (x1 + x2) / 2
elif (f1 * f2) > 0:
x1 = x2
x2 = (x2 + x3) / 2
else:
print()
exact = True
if f1 == 0:
print("[!] Result:", x1)
elif f2 == 0:
print("[!] Result:", x2)
break
# print("Iteration #", i, ": ", x2, sep="")
i += 1
if not exact:
if f1 < 10 ** (-15):
print()
print("[!] Result:", x2)
else:
print("[!] Could not find any root")