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일

0 개 추천

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

Daniel Menewuyelet
Daniel Menewuyelet 2018년 9월 29일
Im such an idiot Thank you very much though.
Stephen23
Stephen23 2018년 9월 29일
@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에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

질문:

2018년 9월 29일

댓글:

2018년 9월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by