forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintersection.py
54 lines (48 loc) · 1.62 KB
/
intersection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
importmath
fromcollections.abcimportCallable
defintersection(function: Callable[[float], float], x0: float, x1: float) ->float:
"""
function is the f we want to find its root
x0 and x1 are two random starting points
>>> intersection(lambda x: x ** 3 - 1, -5, 5)
0.9999999999954654
>>> intersection(lambda x: x ** 3 - 1, 5, 5)
Traceback (most recent call last):
...
ZeroDivisionError: float division by zero, could not find root
>>> intersection(lambda x: x ** 3 - 1, 100, 200)
1.0000000000003888
>>> intersection(lambda x: x ** 2 - 4 * x + 3, 0, 2)
0.9999999998088019
>>> intersection(lambda x: x ** 2 - 4 * x + 3, 2, 4)
2.9999999998088023
>>> intersection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)
3.0000000001786042
>>> intersection(math.sin, -math.pi, math.pi)
0.0
>>> intersection(math.cos, -math.pi, math.pi)
Traceback (most recent call last):
...
ZeroDivisionError: float division by zero, could not find root
"""
x_n: float=x0
x_n1: float=x1
whileTrue:
ifx_n==x_n1orfunction(x_n1) ==function(x_n):
raiseZeroDivisionError("float division by zero, could not find root")
x_n2: float=x_n1- (
function(x_n1) / ((function(x_n1) -function(x_n)) / (x_n1-x_n))
)
ifabs(x_n2-x_n1) <10**-5:
returnx_n2
x_n=x_n1
x_n1=x_n2
deff(x: float) ->float:
"""
function is f(x) = x^3 - 2x - 5
>>> f(2)
-1.0
"""
returnmath.pow(x, 3) - (2*x) -5
if__name__=="__main__":
print(intersection(f, 3, 3.5))