سؤال

I'm trying to code Taylor summation for a function in Matlab, I actually evaluate McLaurin making x=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.

هل كانت مفيدة؟

المحلول

Your code works correctly and plots the correct Taylor polynomial. Your mistake is that you are expecting a 20th degree Taylor polynomial to approximate the sine function on the interval [-100,100]. This is much too optimistic. It gives a decent approximation on [-5,5] and that's about it. Here is the output of your code with a=-9, b=9, where the problems already appear:

sine_approx

Indeed, x^n/n! is about (e*x/n)^n, using a rough version of Stirling's formula. So you need |x| < n/e to avoid a catastrophically large error term, and an even smaller interval (like |x| < n/3 ) to have a good approximation. With n=20, n/3 is 6.66...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top