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)

 Respuesta aceptada

Stephen23
Stephen23 el 29 de Sept. de 2018
Editada: Stephen23 el 29 de Sept. de 2018
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 comentarios

Daniel Menewuyelet
Daniel Menewuyelet el 29 de Sept. de 2018
Im such an idiot Thank you very much though.
Stephen23
Stephen23 el 29 de Sept. de 2018
@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!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Aún no se han introducido etiquetas.

Preguntada:

el 29 de Sept. de 2018

Comentada:

el 29 de Sept. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by