Skip to content

Commit 8a1f84e

Browse files
authored
Update bisection.py
alittle optimization?)
1 parent f8fe8fe commit 8a1f84e

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

arithmetic_analysis/bisection.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -19,23 +19,26 @@ def bisection(function: Callable[[float], float], a: float, b: float) -> float:
1919
...
2020
ValueError: could not find root in given interval.
2121
"""
22-
start: float = a
23-
end: float = b
24-
if function(a) == 0: # one of the a or b is a root for the function
22+
fna: float = function(a)
23+
if fna == 0: # one of the a or b is a root for the function
2524
return a
2625
elif function(b) == 0:
2726
return b
2827
elif (
29-
function(a) * function(b) > 0
28+
fna * function(b) > 0
3029
): # if none of these are root and they are both positive or negative,
3130
# then this algorithm can't find the root
3231
raise ValueError("could not find root in given interval.")
3332
else:
33+
start: float = a
34+
end: float = b
3435
mid: float = start + (end - start) / 2.0
36+
fnmid: float = 0
3537
while abs(start - mid) > 10**-7: # until precisely equals to 10^-7
36-
if function(mid) == 0:
38+
fnmid = function(mid)
39+
if fnmid == 0:
3740
return mid
38-
elif function(mid) * function(start) < 0:
41+
elif fnmid * function(start) < 0:
3942
end = mid
4043
else:
4144
start = mid

0 commit comments

Comments
 (0)