Bisection method relative error

2 次查看(过去 30 天)
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
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
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
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by