Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import matplotlib.pyplot as plt
- def do_bis(fun, a, b):
- c_bis = (a + b) / 2
- if fun(a) * fun(c_bis) < 0:
- return a, c_bis
- return c_bis, b
- def do_falsi(fun, a, b):
- if fun(b) - fun(a) == 0:
- print("Division by zero\n")
- c_falsi = (a * fun(b) - b * fun(a)) / (fun(b) - fun(a))
- if fun(c_falsi) * fun(a) < 0:
- return a, c_falsi
- return c_falsi, b
- def bi_reg_root(fun, a, b, err_max):
- MAX_ITER = 1000
- last_ans = (a + b) / 2
- f = []
- for i in range(MAX_ITER):
- lb, rb = do_bis(fun, a, b)
- lf, rf = do_falsi(fun, a, b)
- if abs(rf - lf) < abs(lb - rb):
- a, b = lf, rf
- else:
- a, b = lb, rb
- ans = (a + b) / 2
- err = abs((ans - last_ans) / last_ans)
- f.append(ans)
- if err < err_max:
- return f
- last_ans = (a + b) / 2
- print(i, " : ", ans)
- return last_ans
- def graph(f):
- plt.plot(range(0, len(f)), f)
- plt.title("Method plot")
- plt.show()
- l = 1
- T = 6
- g = 9.81
- my_function = lambda x: (math.pi * ((x / g) ** (1 / 2)) + math.pi * (((x - l) / g) ** (1 / 2)) - T).real
- graph(bi_reg_root(my_function, 1, 100, 1e-7))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement