Advertisement
George_Ivanov05

0.1

Jun 21st, 2022
949
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  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.  
  18. def math_function(x):
  19.     function = math.pow(x, 3) - 3 * x - 5
  20.     return function
  21.  
  22.  
  23. def bisection_method(num1, num2):
  24.     if math_function(num1) * math_function(num2) >= 0:
  25.         raise SameSigns('Cannot f(a) and f(b) to be with same signs')
  26.  
  27.     middle = 0
  28.     while num2 - num1 >= 0.001:
  29.         middle = (num1 + num2) / 2
  30.         if math_function(middle) * math_function(num1) < 0:
  31.             num2 = middle
  32.         if math_function(middle) == 0.0:
  33.             break
  34.         else:
  35.             num1 = middle
  36.  
  37.     return f"{middle:.4f}"
  38.  
  39. print(bisection_method(a, b))
  40.  
  41.  
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement