Advertisement
George_Ivanov05

bisection_method

Jun 26th, 2022
719
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import math
  2.  
  3. # exp(x) - 2x - 2 = 0
  4. # x3 + 3x - 5
  5.  
  6. try:
  7.     a = int(input())
  8.     b = int(input())
  9. except ValueError:
  10.     raise ValueError('a and b must be integers')
  11.  
  12.  
  13. class SameSigns(Exception):
  14.     pass
  15.  
  16.  
  17. def math_function(x):
  18.     return math.pow(x, 3) - 3 * x - 5
  19.  
  20. def math_function2(x):
  21.     return math.exp(x) - 2 * x - 2
  22.  
  23.  
  24. def bisection_method(num1, num2, func):
  25.     if func(num1) * func(num2) >= 0:
  26.         raise SameSigns('f(a) and f(b) must be with different signs')
  27.     middle = 0
  28.     while num2 - num1 >= 0.001:
  29.         middle = (num1 + num2) / 2
  30.         if func(middle) * func(num1) < 0:
  31.             num2 = middle
  32.         else:
  33.             num1 = middle
  34.         if func(middle) == 0.0:
  35.             break
  36.  
  37.     return f"{middle:.4f}"
Advertisement
RAW Paste Data Copied
Advertisement