Both of the following code give the same result. But I'm not sure where should I put the raise statement.
def bisection(f, start, stop, eps = 1e-5, max_iteration = 100):
for __ in range(max_iteration):
half = start + (stop - start)/2
if abs(f(half)) < eps or half - start < eps:
return half
if f(half) * f(start) > 0:
start = half
else:
stop = half
else:
raise ValueError('Cannot find root in the given range')
Or
def bisection(f, start, stop, eps = 1e-5, max_iteration = 100):
for __ in range(max_iteration):
half = start + (stop - start)/2
if abs(f(half)) < eps or half - start < eps:
return half
if f(half) * f(start) > 0:
start = half
else:
stop = half
raise ValueError('Cannot find root in the given range')
Both methods are same, because you do not have a break
statement in your for
loop.
In the for..else
construct, the else part is executed if the loop is exited without calling the break
statement, if the loop gets exited using a break statement, the else part is not executed, since your loop does not have any break
statement in it, both methods are similar as the else would always get executed.
Given that, I think if you always want to raise a ValueError if the loop does not return
anything, then the second method looks better since its more readable and conveys what exactly you are trying to do. It would take a bit more effort to understand that if the loop gets exited the ValueError would be raised, if you use the first part (and using else
there does not really make sense)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With