Bisection method relative error

Hello everyone, I don't use MATLAB very well. I have a question. If you can help, I'd appreciate.
I have a function below that I have to find its roots using bisection method. I want the for loop to stop on the point where relative error is lower than %0.05. I couldn't understand how I can define n.
f=@(x) log(x)-cos(x)-exp(-x);
x1=1;
x2=2;
xmid=(x1+x2)/2
for i=1:n;
if (f(xmid)*f(x2))<0
x1=xmid;
else
x2=xmid;
end
xmid=(x1+x2)/2;
end
fprintf('The root is: %3.8g\n',xmid)

 採用された回答

Mohammed Hamaidi
Mohammed Hamaidi 2022 年 3 月 17 日
編集済み: Mohammed Hamaidi 2022 年 3 月 18 日

1 投票

Hi
Just use "while" loop with your condition as follows:
f=@(x) log(x)-cos(x)-exp(-x);
x1=1;
x2=2;
xmid=(x1+x2)/2;
while (x2-x1)>0.0005
if (f(xmid)*f(x2))<0
x1=xmid;
else
x2=xmid;
end
xmid=(x1+x2)/2;
end
fprintf('The root is: %3.8g\n',xmid)

4 件のコメント

Sazcl
Sazcl 2022 年 3 月 17 日
Thanks for your time.
But as far as I know, error tolerance is calculated by (upper limit-lower limit)/(2^iteration number) when the exact root is not given in the question.
Actually your code gives the right answer but I don't think it's what the question asks.
Jan
Jan 2022 年 3 月 17 日
@Sazcl: If you do have the mathematical definition of "relative error", it should be easy to insert it in the posted code. Simply use it as condition in the WHILE command.
To avoid an infinite loop, add a counter, which stops the loop after a certain limit, e.g.:
kMax = 1e6;
k = 0;
while <InsertYourCondition> && k < kMax
...
k = k + 1;
end
if k == kMax
error('No convergence')
end
But think twice: Under which circumstances is this possible?
By the way, f(xmid)*f(x2) < 0 does not catch the cases in which xmid or x2 is exactly the root. What a pity, if the root way found and the iteration goes on.
Sazcl
Sazcl 2022 年 3 月 17 日
It really helped, I got it done.
Thank you both.
Jan
Jan 2022 年 3 月 18 日
If this answer solves the problem, please accept it.

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

その他の回答 (1 件)

John
John 2023 年 7 月 31 日

0 投票

function [p, pN] = Bisection_371(a,b,N, tol)
if f(a)*f(b) > 0
disp("IVT does not guarantee a root in [a,b]")
elseif f(a)*f(b) == 0
disp("The root is either a or b")
else
for n = 1:N
p = (a+b)/2;
pN(n) = p;
if f(p) == 0 || (b-a)/2 < tol
break
elseif f(p)*f(a) < 0
b = p;
else
a = p;
end
end
end
end
%f = @(x)x^2 - 1;
function y = f(x)
y = x^2 - 1;
end

1 件のコメント

Jan
Jan 2023 年 8 月 2 日
For numerical reasons it is rather unlikely that the condiotion f(p) == 0 is met exactly. Use a tolerance instead.

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

カテゴリ

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

製品

タグ

質問済み:

2022 年 3 月 17 日

コメント済み:

Jan
2023 年 8 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by