Skip to content

Commit 836bd71

Browse files
CarlosZamGcclausspre-commit-ci[bot]
authored
Add algorithm for approximating the nth root with Newton's Method (#11509)
* Add algorithm for approximating the nth root with Newton's Method * updating DIRECTORY.md * Fix typos in nth_root.py documentation and code * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: cclauss <cclauss@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent b021a69 commit 836bd71

2 files changed

Lines changed: 156 additions & 0 deletions

File tree

‎DIRECTORY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -885,6 +885,7 @@
885885
* [Nevilles Method](maths/numerical_analysis/nevilles_method.py)
886886
* [Newton Forward Interpolation](maths/numerical_analysis/newton_forward_interpolation.py)
887887
* [Newton Raphson](maths/numerical_analysis/newton_raphson.py)
888+
* [Nth Root](maths/numerical_analysis/nth_root.py)
888889
* [Numerical Integration](maths/numerical_analysis/numerical_integration.py)
889890
* [Proper Fractions](maths/numerical_analysis/proper_fractions.py)
890891
* [Runge Kutta](maths/numerical_analysis/runge_kutta.py)
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
"""
2+
Approximate the nth root of a real number using Newton's Method.
3+
4+
The nth root of a real number R can be computed with Newton's method,
5+
which starts with an initial guess x_0 and then iterates using the
6+
recurrence relation:
7+
8+
x_{k + 1} = x_k - ((x_k)**n - R)/(n*(x_k)**(n-1))
9+
10+
The recurrence relation can be rewritten for computational efficiency:
11+
12+
x_{k + 1} = (n-1)/n*x_k + R/(n*(x_k)**(n-1))
13+
14+
Given a tolerance TOL, a stopping criterion can be set as:
15+
16+
abs(x_{k + 1} - x_k) < TOL
17+
18+
References:
19+
- https://en.wikipedia.org/wiki/Nth_root#Using_Newton's_method
20+
- Sauer, T. (2011): Numerical analysis.
21+
USA. Addison-Wesley Publishing Company.
22+
"""
23+
24+
from math import pow # noqa: A004
25+
26+
27+
def nth_root(radicand: float, index: int, tolerance: float = 0.0001) -> float:
28+
"""
29+
Approximate the nth root of the radicand for the given index
30+
31+
Args:
32+
radicand: number from which the root is taken
33+
index: positive integer which is the degree of the root
34+
tolerance: positive real number that establishes the stopping criterion
35+
36+
Returns:
37+
new_approximation: approximation of the nth root of the radicand for the
38+
given index
39+
40+
Raises:
41+
TypeError: radicand is not a real number
42+
TypeError: index is not an integer
43+
ValueError: index is not a positive integer
44+
TypeError: tolerance is not a real number
45+
ValueError: tolerance is not a positive real number
46+
ValueError: math domain error
47+
48+
>>> round(nth_root(9, 2),1)
49+
3.0
50+
51+
>>> int(round(nth_root(-8, 3, 0.001)))
52+
-2
53+
54+
>>> int(round(nth_root(256, 4, 0.001)))
55+
4
56+
57+
>>> round(nth_root(2, 2), 5)
58+
1.41421
59+
60+
>>> round(nth_root(0.25, 2, 0.00000001), 1)
61+
0.5
62+
63+
>>> round(nth_root(-8/27, 3, 0.0000001), 5)
64+
-0.66667
65+
66+
>>> nth_root(0, 2, 0.1)
67+
0.0
68+
69+
>>> nth_root(0.0, 5)
70+
0.0
71+
72+
>>> all(abs(nth_root(k, k, 0.00000001) - k**(1/k)) <= 1e-10 for k in range(1,10))
73+
True
74+
75+
>>> nth_root('invalid input', 3, 0.0001)
76+
Traceback (most recent call last):
77+
...
78+
TypeError: radicand must be a real number, not a str
79+
80+
>>> nth_root(4, 0.5, 0.0001)
81+
Traceback (most recent call last):
82+
...
83+
TypeError: index must be an integer, not a float
84+
85+
>>> nth_root(16, -4, 0.001)
86+
Traceback (most recent call last):
87+
...
88+
ValueError: index must be a positive integer, -4 <= 0
89+
90+
>>> nth_root(4, 2, '0.000001')
91+
Traceback (most recent call last):
92+
...
93+
TypeError: tolerance must be a real number, not str
94+
95+
>>> nth_root(9, 2, -0.01)
96+
Traceback (most recent call last):
97+
...
98+
ValueError: tolerance must be a positive real number, -0.01 <= 0
99+
100+
>>> nth_root(-256, 4, 0.0001)
101+
Traceback (most recent call last):
102+
...
103+
ValueError: math domain error, radicand must be nonnegative for even index
104+
"""
105+
if not isinstance(radicand, (int, float)):
106+
error_message = (
107+
f"radicand must be a real number, not a {type(radicand).__name__}"
108+
)
109+
raise TypeError(error_message)
110+
111+
if not isinstance(index, int):
112+
error_message = f"index must be an integer, not a {type(index).__name__}"
113+
raise TypeError(error_message)
114+
115+
if index <= 0:
116+
error_message = f"index must be a positive integer, {index} <= 0"
117+
raise ValueError(error_message)
118+
119+
if not isinstance(tolerance, (int, float)):
120+
error_message = (
121+
f"tolerance must be a real number, not {type(tolerance).__name__}"
122+
)
123+
raise TypeError(error_message)
124+
125+
if tolerance <= 0:
126+
error_message = f"tolerance must be a positive real number, {tolerance} <= 0"
127+
raise ValueError(error_message)
128+
129+
if radicand < 0 and index % 2 == 0:
130+
error_message = "math domain error, radicand must be nonnegative for even index"
131+
raise ValueError(error_message)
132+
133+
if radicand == 0.0:
134+
return 0.0
135+
136+
# Set initial guess
137+
new_approximation = radicand
138+
# Set old_approximation to enter the loop
139+
old_approximation = new_approximation + tolerance + 0.1
140+
141+
# Iterate as long as the stop criterion is not satisfied
142+
while tolerance <= abs(old_approximation - new_approximation):
143+
old_approximation = new_approximation
144+
# Compute new_approximation with the recurrence relation described above
145+
first_summand = (index - 1) / index * old_approximation
146+
second_summand = radicand / (index * pow(old_approximation, index - 1))
147+
new_approximation = first_summand + second_summand
148+
149+
return new_approximation
150+
151+
152+
if __name__ == "__main__":
153+
import doctest
154+
155+
doctest.testmod()

0 commit comments

Comments
 (0)