MATLAB: Taylor expansion calculation of exp(x^2)

exponential functiontaylor series

Dear Matlab users and experts,
I am aware that the exponential function is standarized as "exp" in Matlab . However, I need to calculate the function value exp(x^2) adjusting the (N) terms in the power series. Can anyone recommend the correct method to compute the function exp(x^2)?
My approach:
x = -3.0:0.1:3.0;
N = 12;
Taylor_p2 = 0;
for n = 0:N
Taylor_p2 = Taylor_p2 + (x.^(2.0.*n))./(factorial(n)); % Taylor_p2 = exp(x^2)
end
isn't giving me the desired value. I am using R2020b Matlab version.
Many thanks in advance.
Bhattarai

Best Answer

The formula for taylor series is correct. Just increase the number of terms.
x = -3.0:0.1:3.0;
N = 12;
Taylor_p2 = 0;
for n = 0:N
Taylor_p2 = Taylor_p2 + (x.^(2.0.*n))./(factorial(n)); % Taylor_p2 = exp(x^2)
end
p2 = exp(x.^2);
err = norm(p2-Taylor_p2);
plot(x, p2);
hold on
plot(x, Taylor_p2, '*')
Result
>> err
err =
9.1544e-05