Need help with this bisection method code!

Im studying for a math test and on a old test there is a task about bisection. The task is to solve x^2=2 with the bisection method and the precision should be with 10 decimals. The problem is that it seems like the teachers recommended solution to the task isn't quite right. Here's the code:
a=1;
b=2;
tol=1e-10;
fa=a*a-2;
fb=b*b-2;
while b-a>tol
c=(a+b)/2;
fc=c+c-2;
if fa*fc<0
b=c;
fb=fc;
elseif fb*fc<0
a=c;
fa=fc;
else
break
end
end
x=c
I keep getting the answer x= 1.000000000087311
What am I doing wrong, have been stuck with this problem for a while now so I might have missed some obvious misstakes
/Johan

 採用された回答

Geoff Hayes
Geoff Hayes 2015 年 1 月 4 日

3 投票

Johan - for the while condition, you probably want the absolute value of the difference to handle the case where the roots could be negative. So just change this line to
while abs(b-a) > tol
Also, look at how you are calculating fc
fc = c+c-2;
This should probably be
fx = c*c-2;
instead, since you are trying to find the root of x^2-2. Try making these two changes and see if that helps find the correct solution.

2 件のコメント

Johan
Johan 2015 年 1 月 4 日
Thanks a lot, the code works now :)
John D'Errico
John D'Errico 2015 年 1 月 4 日
編集済み: John D'Errico 2015 年 1 月 4 日
Note that this is a very good reason why you need to learn about how to provide the function itself. for example...
fun = @(x) x.^2 - 2;
No more typo errors due to typing in that function over and over again. As well, it will now allow you to solve other problems. Hardcoded objective functions are poor programming style, because they tend to create bug just as you had. They force you to edit code just to change a function. What if you miss one or more of the places that function was hard coded in?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeEntering Commands についてさらに検索

質問済み:

2015 年 1 月 4 日

編集済み:

2015 年 1 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by