relative error- can't stop it

조회 수: 2 (최근 30일)
jamshid
jamshid 2011년 3월 28일
[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

답변 (1개)

David Young
David Young 2011년 3월 28일
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
jamshid
jamshid 2011년 3월 28일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by