Advertisement
Guest User

Untitled

a guest
Feb 29th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. import math
  2. import matplotlib.pyplot as plt
  3.  
  4.  
  5. def do_bis(fun, a, b):
  6.     c_bis = (a + b) / 2
  7.  
  8.     if fun(a) * fun(c_bis) < 0:
  9.         return a, c_bis
  10.  
  11.     return c_bis, b
  12.  
  13.  
  14. def do_falsi(fun, a, b):
  15.     if fun(b) - fun(a) == 0:
  16.         print("Division by zero\n")
  17.     c_falsi = (a * fun(b) - b * fun(a)) / (fun(b) - fun(a))
  18.  
  19.     if fun(c_falsi) * fun(a) < 0:
  20.         return a, c_falsi
  21.  
  22.     return c_falsi, b
  23.  
  24.  
  25. def bi_reg_root(fun, a, b, err_max):
  26.     MAX_ITER = 1000
  27.     last_ans = (a + b) / 2
  28.     f = []
  29.     for i in range(MAX_ITER):
  30.         lb, rb = do_bis(fun, a, b)
  31.         lf, rf = do_falsi(fun, a, b)
  32.         if abs(rf - lf) < abs(lb - rb):
  33.             a, b = lf, rf
  34.         else:
  35.             a, b = lb, rb
  36.         ans = (a + b) / 2
  37.         err = abs((ans - last_ans) / last_ans)
  38.         f.append(ans)
  39.         if err < err_max:
  40.             return f
  41.         last_ans = (a + b) / 2
  42.         print(i, " : ", ans)
  43.     return last_ans
  44.  
  45.  
  46. def graph(f):
  47.     plt.plot(range(0, len(f)), f)
  48.     plt.title("Method plot")
  49.     plt.show()
  50.  
  51.  
  52. l = 1
  53. T = 6
  54. g = 9.81
  55. my_function = lambda x: (math.pi * ((x / g) ** (1 / 2)) + math.pi * (((x - l) / g) ** (1 / 2)) - T).real
  56. graph(bi_reg_root(my_function, 1, 100, 1e-7))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement