Help with simple bisection method function while loop

조회 수: 8 (최근 30일)
Timothy Monroe
Timothy Monroe 2021년 2월 24일
답변: Steven Lord 2021년 2월 25일
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