-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecant.py
executable file
·42 lines (34 loc) · 1.07 KB
/
secant.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
from math import *
# INPUT PARAMATERS:
eqn_str = input("equation for y=f(x) > ")
a = float(input("lower limit (a) > "))
b = float(input("upper limit (b) > "))
tolerance = float(input("tolerance value > "))
max_iterations = float(input("maximum number of iterations > "))
fx = eval("lambda x: " + eqn_str) # function representing our equation
line = f"{'':-^3}|{'':-^22}|{'':-^22}|{'':-^22}|{'':-^21}"
# print table headers:
print(line)
print(f"{'n':^2} | {'a':^20} | {'b':^20} | {'c':^20} | {'|(c) - (c*)| < e':^20}")
print(line)
n = 1 # iteration number
fa = fx(a) # function at a
fb = fx(b) # function at b
while n <= max_iterations:
# calculate c
c = ((a * fb) - (b * fa)) / (fb - fa)
fc = fx(c)
err = abs(c - b) # estimated absolute error
# print a row in table
print(f"{n:^2} | {a:^20} | {b:^20} | {c:^20} | {err:^20.10f} ")
if fc == 0 or err < tolerance: # solution is found?
break
# update next interval:
a = b
b = c
fa = fb
fb = fc
n = n + 1
else:
print("Method failed after maximum iterations")
print(line)