Skip to content

Commit 3fad6df

Browse files
committed
maths/numerical_analysis/brents_method.py
1 parent 80fdda3 commit 3fad6df

1 file changed

Lines changed: 9 additions & 7 deletions

File tree

maths/numerical_analysis/brents_method.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
44
Find a root of a function in a bracketing interval using Brent's method.
55
6-
Brent's method combines bisection, secant, and inverse quadratic interpolation to efficiently and robustly find a root of a continuous function. It is guaranteed to converge as long as the root is bracketed.
6+
Brent's method combines bisection, secant, and inverse quadratic interpolation
7+
to efficiently and robustly find a root of a continuous function. It is
8+
guaranteed to converge as long as the root is bracketed.
79
810
See:
911
https://en.wikipedia.org/wiki/Brent%27s_method
@@ -37,11 +39,11 @@ def brent_method(
3739
ValueError: If the root is not bracketed in [lower_bound, upper_bound].
3840
3941
Examples:
40-
>>> brent_method(lambda x: x**3 - 1, -5, 5)
42+
>>> round(brent_method(lambda x: x**3 - 1, -5, 5), 6)
4143
1.0
42-
>>> brent_method(lambda x: x**2 - 4*x + 3, 0, 2)
44+
>>> round(brent_method(lambda x: x**2 - 4*x + 3, 0, 2), 6)
4345
1.0
44-
>>> brent_method(lambda x: x**2 - 4*x + 3, 2, 4)
46+
>>> round(brent_method(lambda x: x**2 - 4*x + 3, 2, 4), 6)
4547
3.0
4648
>>> brent_method(lambda x: x**2 - 4*x + 3, 4, 1000)
4749
Traceback (most recent call last):
@@ -68,7 +70,7 @@ def brent_method(
6870

6971
for _ in range(max_iterations):
7072
if function_upper == 0:
71-
return upper_bound
73+
return round(upper_bound, 12)
7274
if function_previous not in {function_lower, function_upper}:
7375
# Inverse quadratic interpolation
7476
s = (
@@ -112,9 +114,9 @@ def brent_method(
112114
function_lower, function_upper = function_upper, function_lower
113115

114116
if abs(upper_bound - lower_bound) < tolerance or function_upper == 0:
115-
return upper_bound
117+
return round(upper_bound, 12)
116118

117-
return upper_bound
119+
return round(upper_bound, 12)
118120

119121

120122
if __name__ == "__main__":

0 commit comments

Comments
 (0)