>>> bisection(-2, 5) 3.1611328125 >>> bisection(0, 6) 3.158203125 >>> bisection(2, 3) Traceback (most recent call last): ... ValueError: Wrong space!
(a: float, b: float)
| 25 | |
| 26 | |
| 27 | def bisection(a: float, b: float) -> float: |
| 28 | """ |
| 29 | >>> bisection(-2, 5) |
| 30 | 3.1611328125 |
| 31 | >>> bisection(0, 6) |
| 32 | 3.158203125 |
| 33 | >>> bisection(2, 3) |
| 34 | Traceback (most recent call last): |
| 35 | ... |
| 36 | ValueError: Wrong space! |
| 37 | """ |
| 38 | # Bolzano theory in order to find if there is a root between a and b |
| 39 | if equation(a) * equation(b) >= 0: |
| 40 | raise ValueError("Wrong space!") |
| 41 | |
| 42 | c = a |
| 43 | while (b - a) >= 0.01: |
| 44 | # Find middle point |
| 45 | c = (a + b) / 2 |
| 46 | # Check if middle point is root |
| 47 | if equation(c) == 0.0: |
| 48 | break |
| 49 | # Decide the side to repeat the steps |
| 50 | if equation(c) * equation(a) < 0: |
| 51 | b = c |
| 52 | else: |
| 53 | a = c |
| 54 | return c |
| 55 | |
| 56 | |
| 57 | if __name__ == "__main__": |
no test coverage detected