Help with simple bisection method function while loop

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

Réponses (1)

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?

Catégories

En savoir plus sur Programming dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by