How to save each guess / output as an array via Newton's Method?
2 ビュー (過去 30 日間)
古いコメントを表示
Currently doing the Newton's Method for a homework problem.
Here's how the lecture demonstrated this.
x = 3; % Our initial Guess.
f = @(x) x.^2 - 191; % Our equation.
f_prime = @(x) 2*x; % Deriviative of Equation.
tol = 1e-4 % Our Tolerance.
for i = 1:1000 % Let this sucker go up to 1000.
x = x - f(x)/f_prime(x);
if abs(f(x)) < tol
break
end
end
if i == 1000
warning('Newtons''s method did not converge.');
end
approx_root = x; % Root done by computation above.
true_root = sqrt(191); % Actual Root.
disp(abs(true_root - approx_root)); % This is the error.
disp(i) % This is the number of iterations it took.
Now, I don't know how to store each guess into a row vector.
If I wanted to store each guess into a row vector? How would you go about that? I'm certain there's a for loop component to it.
0 件のコメント
回答 (1 件)
madhan ravi
2020 年 7 月 10 日
x = zeros(1e3, 1);
x(1) = 3;
for ii = 2:1e3 % Let this sucker go up to 1000.
x(ii) = x(ii-1) - f(x(ii-1))/f_prime(x(ii-1));
if abs(f(x(ii-1))) < tol
break
end
end
2 件のコメント
madhan ravi
2020 年 7 月 10 日
編集済み: madhan ravi
2020 年 7 月 10 日
f = @(x) x.^2 - 191; % Our equation.
f_prime = @(x) 2*x; % Deriviative of Equation.
tol = 1e-4 % Our Tolerance.
x = zeros(1e3, 1);
x(1) = 3; % Our initial Guess.
for ii = 2:1e3 % Let this sucker go up to 1000.
x(ii) = x(ii-1) - f(x(ii-1))/f_prime(x(ii-1));
if abs(f(x(ii-1))) < tol
break
end
end
if ii == 1000
warning('Newtons''s method did not converge.');
end
approx_root = x; % Root done by computation above.
true_root = sqrt(191); % Actual Root.
disp(abs(true_root - approx_root)); % This is the error.
disp(ii) % This is the number of iterations it took.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!