MATLAB Answers

Taylor expansion calculation of exp(x^2)

80 views (last 30 days)
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)
isn't giving me the desired value. I am using R2020b Matlab version.
Many thanks in advance.

Accepted Answer

Ameer Hamza
Ameer Hamza on 30 Dec 2020
Edited: Ameer Hamza on 30 Dec 2020
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)
p2 = exp(x.^2);
err = norm(p2-Taylor_p2);
plot(x, p2);
hold on
plot(x, Taylor_p2, '*')
>> err
err =
aroj bhattarai
aroj bhattarai on 1 Jan 2021
Dear John D'Errico,
Should you not expect a complex number as a result? The bug is in your code, and how you handle complex results.
Yes, you are right, complex number results are expected which leads to slower convergent for abs(x)>1. For such situation, is there any mathematical solution to get a proper result? Or the real number exponent in the exponential function is fundamentally non-sense and unstable? My apologies for directing the original question into a mathematical discussion rather than the Matlab problem.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!