11import math
2+ from typing import Callable
23
34
4- def intersection (function , x0 , x1 ) :
5+ def intersection (function : Callable [[ float ], float ], x0 : float , x1 : float ) -> float :
56 """
67 function is the f we want to find its root
78 x0 and x1 are two random starting points
9+ >>> intersection(lambda x: x ** 3 - 1, -5, 5)
10+ 0.9999999999954654
11+ >>> intersection(lambda x: x ** 3 - 1, 5, 5)
12+ Traceback (most recent call last):
13+ ...
14+ ZeroDivisionError: float division by zero, could not find root
15+ >>> intersection(lambda x: x ** 3 - 1, 100, 200)
16+ 1.0000000000003888
17+ >>> intersection(lambda x: x ** 2 - 4 * x + 3, 0, 2)
18+ 0.9999999998088019
19+ >>> intersection(lambda x: x ** 2 - 4 * x + 3, 2, 4)
20+ 2.9999999998088023
21+ >>> intersection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)
22+ 3.0000000001786042
23+ >>> intersection(math.sin, -math.pi, math.pi)
24+ 0.0
25+ >>> intersection(math.cos, -math.pi, math.pi)
26+ Traceback (most recent call last):
27+ ...
28+ ZeroDivisionError: float division by zero, could not find root
829 """
9- x_n = x0
10- x_n1 = x1
30+ x_n : float = x0
31+ x_n1 : float = x1
1132 while True :
12- x_n2 = x_n1 - (
33+ if x_n == x_n1 or function (x_n1 ) == function (x_n ):
34+ raise ZeroDivisionError ("float division by zero, could not find root" )
35+ x_n2 : float = x_n1 - (
1336 function (x_n1 ) / ((function (x_n1 ) - function (x_n )) / (x_n1 - x_n ))
1437 )
1538 if abs (x_n2 - x_n1 ) < 10 ** - 5 :
@@ -18,7 +41,7 @@ def intersection(function, x0, x1):
1841 x_n1 = x_n2
1942
2043
21- def f (x ) :
44+ def f (x : float ) -> float :
2245 return math .pow (x , 3 ) - (2 * x ) - 5
2346
2447
0 commit comments