What's wrong in my Taylor series implementation in MATLAB?

2k Views Asked by At

I'm trying to code Taylor summation for a function in Matlab, I actually evaluate McLaurin making $x_0=0$, named a in this code after this notation:

enter image description here

This is the code I've tried out so far:

>> a = -100;
b = 100;
n = 20;
vectorx = linspace(a,b,50);
vectory = [];
sumterms = [];
syms x y a;
y = sin(a);
for i = 1:n
t = (diff(y,i-1) / factorial(i-1)) * (x-0)^(i-1);
sumterms = [sumterms;t];
end;
sumterms
for j = 1:length(vectorx)
x_i = vectorx(j);
aux = 0;
for k = 1:length(sumterms)
sumterm = sumterms(k);
aux = aux + subs(sumterm, [a,x], [0,x_i]);
end
vectory = [vectory;aux];
end
length(vectory)
length(vectorx)
plot (vectorx, vectory)

But I'm not getting correct results I've step over each sentence and I can't really see what's wrong about it.

This is my plot result for sin(x):

enter image description here

And this is plot for exponential(x)

enter image description here

Sumterms results for each appear in the image capture, and they seem to be ok, however I think error is in evaluation.

1

There are 1 best solutions below

2
On BEST ANSWER

You have truncated the series at $n=20$. The error term, for either function, is roughly $\dfrac{|x|^{21}}{ 21!}$. This error is very small when $x$ is small, and is of moderate size when $|x|\approx n/e$, but grows rapidly beyond that. When $x=20$, the size of the error is measured in millions.

So: either narrow down the range of $x$, or use more terms: for $|x|\le 100$, try $100e$ terms.