Bisection method not working. Is my code heading in the right direction?
2 ビュー (過去 30 日間)
古いコメントを表示
x=sym('x');
endpoint_a = input('Plese input your endpoint a: ');
endpoint_b = input('Plese input your endpoint b: ');
tol = input('Plese input your tolerance: ');
n_0 = input('Plese input your maximum iterations : ');
F= input('Plese input your equation : ');
N=0;
a=subs(F,x,endpoint_a);
b=subs(F,x,endpoint_b);
% p= (subs(F,x,endpoint_a)+subs(F,x,endpoint_b))/2;
while(N <= n_0 && not(abs((endpoint_a-endpoint_b)/2) <= tol ))
N= N + 1;
p = (subs(F,x,endpoint_a)+subs(F,x,endpoint_b))/2;
p=b;
if (a*b) > 0
a=p;
else
endpoint_b=p;
end
end
0 件のコメント
回答 (1 件)
John D'Errico
2019 年 9 月 15 日
I had to laugh, as I recognized your coding style from a previous question. Then I remembered your name. Note that
not(abs((endpoint_a-endpoint_b)/2) <= tol)
is the logical equivalent of the simpler
abs((endpoint_a-endpoint_b)/2) > tol
There is no need to make things more complicated than they need be.
Ok, given that, you are making a reasonable effort in these. Your problem in this one is an error of thought. You compute this:
p = (subs(F,x,endpoint_a)+subs(F,x,endpoint_b))/2;
The bisection method wants to evaluate the functino F at the midpoint of the current interval. So it needs to compare the values of F(a), f(b), and the value at the midpoint, thus F((a+b)/2).
What did you do? You computed the new point p as (F(a) + F(b))/2.
Next, you don't want to test if a*b is less than zero! In fact, here a and b are not even defined in your code. You do want to test if F(a)*F(b) is less than zero. That ensures that F(a) and F(b) have different signs.
So, you are going in a reasonable directino in this code. Not there yet. I think you can fix this, as your basic logic in the code is not bad. So try again, and show what you have if there is still a problem. I have confidence that you will get this right though on your own, with just a small nudge or two.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!