Help with simple bisection method function while loop
13 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Steven Lord
on 25 Feb 2021
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
y = f(1)
isYSmallerThanTol = y < tol
So good enough, I've found my root, right?
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!