Plotting approximation error in Newton-Raphson

Hello all,
In a script I'm trying to find roots of a function by Newton-Raphson method. In each iteration I'm finding and printing the relative approximation error.
What I want is, instead of printing them I would like plot my function and my relative approximation error in each iteration.
Any help is much appreciated.
My script file:
function [r] = newton(x1)
n = 1000;
tol_error = 0.001;
r = x1;
for t=1:n
x_plus = x1 - (my_func(x1)/my_func_diff(x1));
approx_error(t) = abs((x_plus - x1)/(x_plus))*100;
if (approx_error(t) < tol_error)
display(t);
display(approx_error(t));
r = x_plus;
return;
else
x1 = x_plus;
end
end
end
function y = my_func_diff(x)
y = 3*(x^2) - 20*x - 43;
end
function y = my_func(x)
y = x^3 - 10*(x^2) - 43*x + 52;
end

 採用された回答

Mischa Kim
Mischa Kim 2014 年 3 月 15 日
編集済み: Mischa Kim 2014 年 3 月 16 日

1 投票

Hidir, I assume you are using a while-loop that you execute until the relative error is smaller than some given tolerance. Something like:
ii = 0; % define a loop index (= iteration number)
while (abs(err) > tol)
ii = ii + 1; % increment loop index
... % do some computations
err(ii) = ... % compute and save relative error as vector
end
plot(ii,err,'rs',ii,fun) % plot error along with function value

3 件のコメント

Hidir
Hidir 2014 年 3 月 18 日
Doesn't seem to be working mate. I included my code, it might help you.
Mischa Kim
Mischa Kim 2014 年 3 月 18 日
編集済み: Mischa Kim 2014 年 3 月 18 日
Here you go:
function [r] = newton(x1)
n = 1000;
tol_error = 0.00001;
r = x1;
for t=1:n
x_plus = x1 - (my_func(x1)/my_func_diff(x1));
approx_error(t) = abs((x_plus - x1)/(x_plus))*100;
fun_val(t) = my_func(x1); % save function values as vector
if (approx_error(t) < tol_error)
display(t);
display(approx_error(t));
r = x_plus;
break; % use break instead of return
else
x1 = x_plus;
end
end
plot(1:t,approx_error,'rs-',1:t,fun_val,'bd-')
grid
end
Hidir
Hidir 2014 年 3 月 19 日
Works like a charm. Ty !

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeApp Building についてさらに検索

タグ

質問済み:

2014 年 3 月 15 日

コメント済み:

2014 年 3 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by