MATLAB for-loop to compute Taylor series of cos(x) for any n

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 11K views
Tuttle917
Messages
1
Reaction score
0
I was hoping somebody would be able to help me as I am pretty new to Matlab. I am trying to create a for-loop to describe the taylor series expansion of cos(x)= (-1)^n*x^2n/(2n)! and to see how it converges towards cos(x). Below is the code that I have used to plot the different orders of n, but I was wondering if there was a way to make this work for any value of n?

n=0;
for x = -6:0.25:6
n=n+1;
y(n)=x;
F(n)=cos(x);
F0(n)=1;
F2(n)=1-0.5*x^2;
F4(n)=1-0.5*x^2+(1/24)*x^4;
end
plot(y,F,y,F0,y,F2,y,F4)
axis([-6 6 -1.5 1.5])

I have tried

n=0;
for x=(-2:.25:2)
n=n+1;
Y(n)=x;
F(n)=cos(x);
G(n)=1+(-1)^n*x^(2*n)/prod(1:2*n);
end
plot(y,G)

but the plot for G does not come close to cos(x) as the values of n are not constant and the plot goes to zero. Any help would be greatly appreciated.
 
Physics news on Phys.org
The solution is to make a function that will take in as arguments n and x and will return the approximated cosine.

Tuttle917 said:
G(n)=1+(-1)^n*x^(2*n)/prod(1:2*n);
This is not correct, as it is the sum of the 0th term and the nth term. There should be a loop in order to sum over n.

Also, MATLAB has a factorial function, so factorial(2*n) should be used instead of prod(1:2*n).
 
MATLAB CODE FOR CALCULATION TAYLOR SERIES a*cos(bx)^2

clear all
clc

a=input('enter an a value ');
b=input('enter an b value ');
x1=input('enter an x1 value ');
x2=input('enter an x2 value ');
f(x1)=a*cos(b*x1)^2;
f1(x1)=-2*a*b*cos(b*x1)*sin(b*x1); %diff(f(x1))
f2(x1)=2*a*b^2*sin(b*x1)^2 - 2*a*b^2*cos(b*x1)^2; %diff(f1(x1))
f3(x1)=8*a*b^3*cos(b*x1)*sin(b*x1);%diff(f2(x1))


y=f(x1)+f1(x1)*(x2-x1)+(f2(x1)*(x2-x1)^2)+(f3(x1)*(x2-x1)^3)/6 f(x2)=a*cos(b*x2)^2;
f1(x2)=-2*a*b*cos(b*x2)*sin(b*x2); %diff(f(x2))
f2(x2)=2*a*b^2*sin(b*x2)^2 - 2*a*b^2*cos(b*x2)^2; %diff(f1(x2))
f3(x2)=8*a*b^3*cos(b*x2)*sin(b*x2); %diff(f2(x2))

z=f(x2)+f1(x2)*(x2-x1)+(f2(x2)*(x2-x1)^2)+(f3(x2)*(x2-x1)^3)/6

error=((y-z)/y)*100