How do i write the function for the taylor polynomial of cos(x) using for loops and no anonymous function

10 vues (au cours des 30 derniers jours)
Pn is the taylor polynomial of the degree (at most) n centred at x0=0 for the function cos(x)
The function should take inputs a and n and return Pn evaluated at x=a
function Pn = taylor_cos(a,n)
x=a;
Pn=1;
for i=1:n;
addterm=((-1)^i)*(x^(2*i))/factorial(2*(i));
Pn=Pn+addterm;
end
% thats my version but for some reason its incorrect
  6 commentaires
Wan Ji
Wan Ji le 2 Sep 2021
Would you like to show us the website of the grader, I have tried many of the cody questions in Matlab Community Cody. And always I get full marks
B
B le 2 Sep 2021
apologise i had inputed the modifed code incorrectly, its working now

Connectez-vous pour commenter.

Réponse acceptée

Wan Ji
Wan Ji le 2 Sep 2021
If a large x is selected, then use
function Pn = taylor_cos(a,n)
x=mod(abs(a),2*pi); %
if(x>=pi)
x = 2*pi-x;
end
Pn=1;
for i=1:n
addterm=((-1)^i)*(x^(2*i))/factorial(2*(i));
Pn=Pn+addterm;
end

Plus de réponses (1)

John D'Errico
John D'Errico le 2 Sep 2021
We can see how well it works. Your code is below.
Now, let me test it out, in a symbolic form.
syms X
P8 = taylor_cos(X,4)
P8 = 
Is that a correct Taylor expansion for cos(X)?
Yes. In fact, it is.
taylor(cos(X),'order',10)
ans = 
Does it correctly extimate cos(X), for reasonably small X?
taylor_cos(0.1,4)
ans = 0.9950
cos(0.1)
ans = 0.9950
It seems to predict reasonably well.
My guess is you are hoping this will predict correctly for large values of X. And that is of course not true.
taylor_cos(20,10)
ans = 2.0966e+07
Yes, that is garbage. Perhaps you need to do some reading about convergence of infinite series. Even if this series will converge in theory, after a vast number of terms, this does not mean you will expect it to converge in practice, using computation with a finite number of decimal digits.
function Pn = taylor_cos(a,n)
x=a;
Pn=1;
for i=1:n;
addterm=((-1)^i)*(x^(2*i))/factorial(2*(i));
Pn=Pn+addterm;
end
end

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by