Matlab taking a very long time to give output when my error limit is low

I am finding roots by the false position method. User inputs are upper and lower boundary (yu,yl) and error limit (err)
It works, except when you give it too large of numbers to work with. Whenever I put in the error as 1 and yu,yl as say (-5,7) it will work. But when I try that with a error limit as (.00001) or so, then matlab gets stuck on run and won't ever give the output.
clc
clear all
close all
%, press run, and then enter values you'd like
f=@(x)(x.^3+7*x.^2-33*x-135);
yl = input('type approximated lower boundary:');
yu = input('type approximated upper boundary:');
err=input('Type desired approximate error limit:');
if (yl*yu) > 0
disp(' the appriximation boundaries cannot have the same sign, final warning.');
%if values do not produce a negative number give better boundaries
end
while (abs(yu-yl)>err) %basically how close do you want the boundaries to go
ynew = yu -(f(yu)*(yl - yu))/(f(yl) - f(yu));
if (f(yl)*f(ynew) < 0)
yu=ynew;
else
yl=ynew;
end
end
fprintf('The root of this equation given your error limit is=%f', ynew);

2 commentaires

what inputs are you giving?
two esimated boundaries, one negative and one positive. and an error limit.
When you put in something as simple as -60,60 and .01. Matlab stays stuck on run and never fully gives an output

Connectez-vous pour commenter.

 Réponse acceptée

Hi Anthony,
The reason for this is that one of the initial boundaries, say the lower one, never gets changed while the upper boundary (which is updated by ynew) gets closer and closer to the answer y_root. But unless the initial yl is a totally lucky guess, abs(yl-y_root) can never become really small. So the loop never terminates.
One way out of this is to compare the ' new ynew' to the ynew in the previous iteration. That difference should become small. That's what the code below does.
Also, your input test (yl*yu) > 0 should be (f(yl)*f(yu)) > 0. It's the function that has to be on either side of zero, not the y locations.
f=@(x)(x.^3+7*x.^2-33*x-135);
plot(-10:.01:10,f(-10:.01:10))
yl = -8;
yu = 0;
err = 1e-7;
if (f(yl)*f(yu)) > 0
disp(' the function at boundaries cannot have the same sign, final warning.');
%if values do not produce a negative number give better boundaries
end
yold = yu;
ynew = yl;
count = 0;
while (abs(yold-ynew) > err)
yold = ynew;
ynew = yu -(f(yu)*(yl - yu))/(f(yl) - f(yu));
if (f(yl)*f(ynew) < 0)
yu = ynew;
else
yl = ynew;
end
count = count+1;
end
count
ynew
f(ynew) % small, but difference from zero not the same as err criterion
% (they are related by df/dy at the root)

Plus de réponses (0)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by