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 Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by