Newton's method(calculating the angel)

2 ビュー (過去 30 日間)
Ahmed Alhawaj
Ahmed Alhawaj 2020 年 3 月 15 日
回答済み: Sriram Tadavarty 2020 年 3 月 16 日
%% Newton's method
w = 30; h = 30; c = 3.5; % In inches
f = @(theta) w*sind(theta) - h*cosd(theta) - c;
fp = @(theta) w*cosd(theta)+h*sind(theta);
theta_newt(1) = 49.49; % Set initial guess
tol=0.4771;
n=1;
while n==1:50
fe = f(theta_newt(1));
fpe = fp(theta_newt(1));
theta_newt(n+1) = theta_newt(n) - fe(n)/fpe(n);
if theta_newt(n+1)>= 49.73-tol || theta_newt(n+1)< 49.73+tol
theta=theta_newt(n+1);
break
end
n = n + 1;
end
I am trying to run this code but it seems that the loop isnt working properly
how would I fix that?
Also,How would I show how many iteration it takes to come up with the wanted angle?
  2 件のコメント
John D'Errico
John D'Errico 2020 年 3 月 15 日
編集済み: John D'Errico 2020 年 3 月 15 日
Why are you using Newton's method anyway? Why not use fzero? Never write your own solver code.
That you should not be writing your own solvers is evidenced by you use of non-working constructs. For example:
while n==1:50
That is not how you construct a while loop.
Ahmed Alhawaj
Ahmed Alhawaj 2020 年 3 月 15 日
how do i fix that?

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

回答 (1 件)

Sriram Tadavarty
Sriram Tadavarty 2020 年 3 月 16 日
Hi Ahmed,
To make the code working, perform the following changes:
  • Update the while loop with proper condition
  • Calculate fe and fpe for each n
  • Do not access the fe and fpe with indexing variable, since it is a scalar
This leads to following update in the while loop
while n <= 50 % Proper loop condition
fe = f(theta_newt(n)); % Calculate for each n
fpe = fp(theta_newt(n)); % Calculate for each n
theta_newt(n+1) = theta_newt(n) - fe/fpe; % Remove the indexing here
if theta_newt(n+1)>= 49.73-tol || theta_newt(n+1)< 49.73+tol
theta=theta_newt(n+1);
break
end
n = n + 1;
end
This will fix the loop operation.
Hope this helps.
Regards,
Sriram

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by