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 ExchangeGet 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