Skip to content

Commit

Permalink
added type hints and doctests to arithmetic_analysis/newton_method.py (
Browse files Browse the repository at this point in the history
…TheAlgorithms#2259)

* added type hints and doctests to arithmetic_analysis/newton_method.py

Continuing TheAlgorithms#2128
Also changed some variable names, made them more descriptive.

* Added type hints and doctests to arithmetic_analysis/newton_method.py

added a type alias for Callable[[float], float] and cleaned up the exception handling

* added type hints and doctests to arithmetic_analysis/newton_method.py

improved exception handling

* Update newton_method.py

Co-authored-by: Christian Clauss <cclauss@me.com>
  • Loading branch information
2 people authored and stokhos committed Jan 3, 2021
1 parent e49a736 commit 7273249
Showing 1 changed file with 36 additions and 11 deletions.
47 changes: 36 additions & 11 deletions arithmetic_analysis/newton_method.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,48 @@
"""Newton's Method."""

# Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method


# function is the f(x) and function1 is the f'(x)
def newton(function, function1, startingInt):
x_n = startingInt
from typing import Callable

RealFunc = Callable[[float], float] # type alias for a real -> real function


# function is the f(x) and derivative is the f'(x)
def newton(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)
while True:
x_n1 = x_n - function(x_n) / function1(x_n)
if abs(x_n - x_n1) < 10 ** -5:
return x_n1
x_n = x_n1
try:
next_guess = prev_guess - function(prev_guess) / derivative(prev_guess)
except ZeroDivisionError:
raise ZeroDivisionError("Could not find root")
if abs(prev_guess - next_guess) < 10 ** -5:
return next_guess
prev_guess = next_guess


def f(x):
def f(x: float) -> float:
return (x ** 3) - (2 * x) - 5


def f1(x):
def f1(x: float) -> float:
return 3 * (x ** 2) - 2


Expand Down

0 comments on commit 7273249

Please sign in to comment.