Newton's method(calculating the angel)

2 次查看(过去 30 天)
%% 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.

请先登录,再进行评论。

回答(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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by