Bisection Code Not Working
1 view (last 30 days)
Show older comments
I have been tasked to create my own bisection method code. I written what I believe to be a fairly robust code, but for some reason the code is not returning a correct value. My code is below. xL represents the lower "x", xU represents the upper "x", tol represents the tolerance, and maxiter represents the maximum number of times the code is to be run.
function[x,int]=bisection(xL, xU, tol, maxiter)
iter=0;
while(1);
xR=(xL+xU)/2;
if (((3/500).*((xR.^3)-(18.535.*xR.^2)+(25.697.*xR)+28.099))*((3/500).*((xL.^3)-(18.535.*xL.^2)+(25.697.*xL)+28.099))<0);
xR=xU;
iter=iter+1;
if ((abs(xR-xU)<tol));
break;
end
end
if (((3/500).*((xR.^3)-(18.535.*xR.^2)+(25.697.*xR)+28.099))*((3/500).*((xU.^3)-(18.535.*xU.^2)+(25.697.*xU)+28.099))<0);
xR=xL;
iter=iter+1;
if((abs(xR-xL)<tol));
break;
end
end
if(iter>maxiter);
break;
end
end
int=iter
x=xR
For example, here is the output for the code:
>> bisection(0, 5, 0.003, 20)
int =
1
x =
5
ans =
5
Any clues as to why my code would be giving answers that are not correct would be greatly appreciated.
0 Comments
Answers (1)
Jan
on 13 Oct 2014
Edited: Jan
on 13 Oct 2014
I'm missing a hint, why you assume that the answer is wrong. All we see is some code and the answers it gives. But we cannot guess what answer you expect.
It is strange that you hard code the function inside the bisection code. In addition you update xR in each iteration - to the same value, but the bisection means, that you update the upper and lower limits.
In addition you compare the function values at xR and xL at first and update xR on demand. Then you check the values at xR and xU. So you have 2 iterations per loop. Look at a defintion of the bisection method either in the script of your lesson or ask wikipedia. One comparison per loop iteration should be enough. If the sign change is not inside the interval [xL xR] it must be inside [xR xU]. Then update the lower or upper limit accordingly by xL=xR or xU=xR until the distance of xU and xL are below the limit.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!