Please help me in debugging my code?

I wrote a code which finds roots using the bisection method but the problem is its just showing up my answer as zero so if you are willing to help me I am very happy.
first_function = @ (x) cos(x)-2*x;
x_upper = 4;
x_lower = -5;
x_mid = (x_lower + x_upper)/2;
i=0;
while abs(x_mid) > 10^-8
if (first_function(x_mid))*(first_function(x_lower))<0
x_lower=x_mid;
else
x_upper = x_mid;
end
x_mid = (x_lower + x_upper)/2;
i=i+1;
end
fprintf('The root is %g and the number of iteration is %g\n ', x_mid,i)

 采纳的回答

Stephen23
Stephen23 2018-9-29
编辑:Stephen23 2018-9-29
The bug is on these lines:
if (first_function(x_mid))*(first_function(x_lower))<0
x_lower = x_mid;
else
x_upper = x_mid;
end
Think about what that comparison actually does (don't just blindly implement some formula you found online): if the difference in sign is negative, then the intersect must be in between. So if you test the lower bound and the sign is negative, then you need to reassign the upper bound value. And vice versa. It really does not matter which way you code this (i.e. test the upper or test the lower, you might find both online), as long as you change the other bound if the sign is negative.
After I fixed this (and the ambiguous parentheses), the code worked perfectly:
f = @(x)cos(x)-2.*x;
a = +4;
b = -5;
h = (a+b)/2;
k = 0;
while abs(f(h)) > 1e-8
if (f(a)*f(h))<0
b = h;
else
a = h;
end
h = (a+b)/2;
k = k+1;
end
fprintf('The root is %g and the number of iteration is %d\n ',h,k)
Prints:
The root is 0.450184 and the number of iteration is 26

2 个评论

Im such an idiot Thank you very much though.
@Daniel Menewuyelet: it is easy to get stuck looking at a problem, and a fresh pair of eyes often helps. Remember to accept my answer if it helped you!

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Get Started with Statistics and Machine Learning Toolbox 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by