Reputation: 71
I made a bisection calculation using python with a loop condition. the loop stops with 2 conditions, reaching a maximum iteration or maximum error.
but when I run, it always ends with 2 iterations.
when I delete the maximum error requirement, the iteration runs up to the maximum iteration but when I delete the iteration requirement, iterates only 2 times.
Please help me. Thank you.
def bisection(f, Xl, Xu, max_eA, iteration):
x_l = Xl
x_u = Xu
eA = 0
Xr = (x_l + x_u)/2
total_iter = 0
if f(Xl)*f(Xu) >= 0:
print("Bisection method fails.")
return None
while eA < max_eA and total_iter < iteration+1:
print("iteration", total_iter+1)
xr_old = Xr
print("xr old",xr_old)
Xr = (x_l + x_u)/2
print("Xr now", Xr)
f_xr = f(Xr)
if f_xr == 0:
print("Found exact solution.")
print("Xr fix", Xr)
return Xr
elif f(x_l)*f_xr < 0:
x_l = x_l
x_u = Xr
print("x_l use",x_l)
print("x_u use",x_u)
elif f(x_l)*f_xr > 0:
x_l = Xr
x_u = x_u
else:
print("Bisection method fails.")
return None
xr_new = Xr
print("xr new",xr_new)
print("xr old 2", xr_old)
print("ea use",eA)
eA = abs((xr_new-xr_old)/xr_new)
print("max ea",max_eA)
print("eA after calculate", eA)
total_iter=total_iter+1
return (x_l + x_u)/2
f = lambda x: ((10000000 * (1.2 ** x)) / ((1.2 ** x) - 1))\
+\
((-10000000*x) / ((1.2 ** x) - 1))\
+\
10000000
bisection(f,5,10,0.0001,20)
Upvotes: 1
Views: 92
Reputation: 425
The code iterates only two times because in the second iteration the value of eA
becomes greater than max_eA
, and that is obvious.
After removing the condition of eA
from the while loop you will get the desired output for 21 iterations.
The output of your code is
iteration 1
xr old 7.5
Xr now 7.5
xr new 7.5
xr old 2 7.5
ea use 0
max ea 0.0001
eA after calculate 0.0
iteration 2
xr old 7.5
Xr now 8.75
x_l use 7.5
x_u use 8.75
xr new 8.75
xr old 2 7.5
ea use 0.0
max ea 0.0001
eA after calculate 0.14285714285714285
As you can see from the output, in the second iteration the value of eA
is 0.14285714285714285
and the value of max_ea
is 0.0001
. So, the while loop fails.
Upvotes: 1