I'm writing a function that calculates the Taylor series of any Function.
syms x
y=cos(x);
y0=0;
a=0;
for i=0:25
diff(y,i); %%Gives the derivative formula
y0=y0+diff(y,i)*((x-a)^i)/factorial(i); %%sums every new element of the series
end
x=0:0.1:2*pi;
res = subs(y0,x);
plot(x,res,x,cos(x))
This is the Matlab code.
My problem is that it graphs cos(2x)
instead of cos(x)
, similarly it graphs ln(2x)
instead of ln(x)
and so on.
I have checked the factorials and they appear to be correct. What could be the problem, have I messed up the series or have I made a Matlab mistake?
You are constructing the Taylor polynomial around the point x
with incrementx-a
, that is, you are computing an approximation for
f(x+(x-a))=f(2*x-a)
Now as a=0
, this means that as observed, you get f(2*x)
.
You would need to evaluate the derivatives at a
to get the correct coefficients.
y0=y0+subs(diff(y,i),a)*((x-a)^i)/factorial(i); %%sums every new element of the series