relative error- can't stop it

2 views (last 30 days)
jamshid
jamshid on 28 Mar 2011
[EDIT: 20110610 00:13 CDT - reformat - WDR]
Hi
I need help to write up a program which makes simple iterations. I don't know how to implement relative error and make it stop when error gets to 0.00001%.
here is my code:
%simple iteration method
f=input('f(x)=','s'); %you input the function, already re-arranged for calculations
tol='error tolerance=1e-5'; %error tolerance is defined by program
if length(tol)==0, tol=1e-5; end
x1=input('first guess=');
x=x1; fx=eval(f);
for i=1:1000000000
x=fx;
ff=eval(f);
fx=eval(f);
fprintf('i = %g, x = %g, fx = %g\n',i,x,fx)
end
Thank you for help

Answers (1)

David Young
David Young on 28 Mar 2011
To compute the relative error (assuming you're trying to find a stationary point of the function), after computing ff, subtract ff from x and take the absolute value. Then maybe you should divide that by the absolute value of x, but that depends on how you define relative error.
Then use a conditional statement (an "if" statement) to test whether the error is less than the tolerance, and use "break" to stop the loop if it is.
Other points to note:
  • 0.00001% is 1e-7, not 1e-5.
  • You can save computation time by using fx = ff instead of fx = eval(f). You do this after testing the error of course.
  1 Comment
jamshid
jamshid on 28 Mar 2011
I tried to do it, but my error is not calculated with a new value of fx. so it always gets value of 0. then I tried to make condition if abs(fx)<tol, break, end but this doesn't execute the process. it just stops.

Sign in to comment.

Categories

Find more on Startup and Shutdown 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!