forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnewton_method.py
More file actions
Latest commit
54 lines (44 loc) · 1.48 KB
/
Copy pathnewton_method.py
File metadata and controls
54 lines (44 loc) · 1.48 KB
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
"""Newton's Method."""
# Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method
fromcollections.abcimportCallable
RealFunc=Callable[[float], float] # type alias for a real -> real function
# function is the f(x) and derivative is the f'(x)
defnewton(
function: RealFunc,
derivative: RealFunc,
starting_int: int,
) ->float:
"""
>>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3)
2.0945514815423474
>>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -2)
1.0
>>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -4)
1.0000000000000102
>>> import math
>>> newton(math.sin, math.cos, 1)
0.0
>>> newton(math.sin, math.cos, 2)
3.141592653589793
>>> newton(math.cos, lambda x: -math.sin(x), 2)
1.5707963267948966
>>> newton(math.cos, lambda x: -math.sin(x), 0)
Traceback (most recent call last):
...
ZeroDivisionError: Could not find root
"""
prev_guess=float(starting_int)
whileTrue:
try:
next_guess=prev_guess-function(prev_guess) /derivative(prev_guess)
exceptZeroDivisionError:
raiseZeroDivisionError("Could not find root") fromNone
ifabs(prev_guess-next_guess) <10**-5:
returnnext_guess
prev_guess=next_guess
deff(x: float) ->float:
return (x**3) - (2*x) -5
deff1(x: float) ->float:
return3* (x**2) -2
if__name__=="__main__":
print(newton(f, f1, 3))