1
1
import math
2
+ from typing import Callable
2
3
3
4
4
- def intersection (function , x0 , x1 ) :
5
+ def intersection (function : Callable [[ float ], float ], x0 : float , x1 : float ) -> float :
5
6
"""
6
7
function is the f we want to find its root
7
8
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
8
29
"""
9
- x_n = x0
10
- x_n1 = x1
30
+ x_n : float = x0
31
+ x_n1 : float = x1
11
32
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 - (
13
36
function (x_n1 ) / ((function (x_n1 ) - function (x_n )) / (x_n1 - x_n ))
14
37
)
15
38
if abs (x_n2 - x_n1 ) < 10 ** - 5 :
@@ -18,7 +41,7 @@ def intersection(function, x0, x1):
18
41
x_n1 = x_n2
19
42
20
43
21
- def f (x ) :
44
+ def f (x : float ) -> float :
22
45
return math .pow (x , 3 ) - (2 * x ) - 5
23
46
24
47
0 commit comments