Effacer les filtres
Effacer les filtres

Newton's method(calculating the angel)

2 vues (au cours des 30 derniers jours)
Ahmed Alhawaj
Ahmed Alhawaj le 15 Mar 2020
%% 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 commentaires
John D'Errico
John D'Errico le 15 Mar 2020
Modifié(e) : John D'Errico le 15 Mar 2020
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 le 15 Mar 2020
how do i fix that?

Connectez-vous pour commenter.

Réponses (1)

Sriram Tadavarty
Sriram Tadavarty le 16 Mar 2020
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

Catégories

En savoir plus sur Econometrics Toolbox dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by