Advertisement
Pug_coder

Untitled

Jun 13th, 2023
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. def equation(x):
  2. return 2 * x**3 + 2 * x**2 - 2 * x - 7
  3.  
  4.  
  5. def bisection_method(a, b, tolerance=1e-3, max_iterations=100):
  6. if equation(a) * equation(b) >= 0:
  7. raise ValueError("The equation may not have a root in the given interval")
  8.  
  9. for iteration in range(max_iterations):
  10. c = (a + b) / 2
  11. if equation(c) == 0 or abs(b - a) / 2 < tolerance:
  12. return c, iteration
  13. if equation(c) * equation(a) < 0:
  14. b = c
  15. else:
  16. a = c
  17.  
  18. raise ValueError("The method did not converge")
  19.  
  20. # Solve the equation using the bisection method
  21. a = -10
  22. b = 10
  23. root, iteration = bisection_method(a, b)
  24. print("Root:", root)
  25. print("Value at the root:", equation(root))
  26. print("Iteration:", iteration)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement