Help with simple bisection method function while loop

6 次查看(过去 30 天)
I am writing a simple root finding bisection method function using a while loop and can't seem to get it to cycle through once i get first correction. Any help is much appreciated.
function [x] = bisection2(x1,x2,tol)
%UNTITLED2 Summary of this function goes here
f=@(x) cos((pi/2)*x)/(1-x^2);
x= (x1+x2)/2;
p=f(x);
i=0;
if p<=tol
fprintf('A Root at x = %f was found in 1 iterations with an error of \n' , x,i)
return
end
while p > tol
i= i+1;
x= (x1+x2)/2;
p=f(x);
if sign(p)==sign(f(x1))
x1=x;
fprintf('Iteration: %f x tested: %f Error Found: %f \n',i,x,p)
return
end
if sign(p)== sign(f(x2))
x2=x;
fprintf('Iteration: %f x tested: %f Error Found: %f \n',i,x,p)
return
else
disp('Root not Bounded!')
return
end
end
end

回答(1 个)

Steven Lord
Steven Lord 2021-2-25
Let's say your function was:
f = @(x) -x.^2;
and your tolerance was 1e-6. Is the tolerance satisfied if I evaluate f at x = 1?
tol = 1e-6
tol = 1.0000e-06
y = f(1)
y = -1
isYSmallerThanTol = y < tol
isYSmallerThanTol = logical
1
So good enough, I've found my root, right?

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by