1313
1414from collections .abc import Callable
1515
16+
1617def brent_method (
1718 function : Callable [[float ], float ],
1819 lower_bound : float ,
@@ -52,8 +53,7 @@ def brent_method(
5253 function_upper = function (upper_bound )
5354 if function_lower * function_upper >= 0 :
5455 error_message = (
55- "Root is not bracketed in the interval "
56- f"[{ lower_bound } , { upper_bound } ]."
56+ f"Root is not bracketed in the interval [{ lower_bound } , { upper_bound } ]."
5757 )
5858 raise ValueError (error_message )
5959
@@ -72,21 +72,44 @@ def brent_method(
7272 if function_previous not in {function_lower , function_upper }:
7373 # Inverse quadratic interpolation
7474 s = (
75- lower_bound * function_upper * function_previous
76- / ((function_lower - function_upper ) * (function_lower - function_previous ))
77- + upper_bound * function_lower * function_previous
78- / ((function_upper - function_lower ) * (function_upper - function_previous ))
79- + previous_bound * function_lower * function_upper
80- / ((function_previous - function_lower ) * (function_previous - function_upper ))
75+ lower_bound
76+ * function_upper
77+ * function_previous
78+ / (
79+ (function_lower - function_upper )
80+ * (function_lower - function_previous )
81+ )
82+ + upper_bound
83+ * function_lower
84+ * function_previous
85+ / (
86+ (function_upper - function_lower )
87+ * (function_upper - function_previous )
88+ )
89+ + previous_bound
90+ * function_lower
91+ * function_upper
92+ / (
93+ (function_previous - function_lower )
94+ * (function_previous - function_upper )
95+ )
8196 )
8297 else :
8398 # Secant method
84- s = upper_bound - function_upper * (upper_bound - lower_bound ) / (function_upper - function_lower )
99+ s = upper_bound - function_upper * (upper_bound - lower_bound ) / (
100+ function_upper - function_lower
101+ )
85102
86103 conditions = [
87- not ((3 * lower_bound + upper_bound ) / 4 < s < upper_bound if upper_bound > lower_bound else upper_bound < s < (3 * lower_bound + upper_bound ) / 4 ),
88- bisect_flag and abs (s - upper_bound ) >= abs (upper_bound - previous_bound ) / 2 ,
89- not bisect_flag and abs (s - upper_bound ) >= abs (previous_bound - previous_step ) / 2 ,
104+ not (
105+ (3 * lower_bound + upper_bound ) / 4 < s < upper_bound
106+ if upper_bound > lower_bound
107+ else upper_bound < s < (3 * lower_bound + upper_bound ) / 4
108+ ),
109+ bisect_flag
110+ and abs (s - upper_bound ) >= abs (upper_bound - previous_bound ) / 2 ,
111+ not bisect_flag
112+ and abs (s - upper_bound ) >= abs (previous_bound - previous_step ) / 2 ,
90113 bisect_flag and abs (upper_bound - previous_bound ) < tolerance ,
91114 not bisect_flag and abs (previous_bound - previous_step ) < tolerance ,
92115 ]
@@ -119,4 +142,5 @@ def brent_method(
119142
120143if __name__ == "__main__" :
121144 import doctest
122- doctest .testmod ()
145+
146+ doctest .testmod ()
0 commit comments