Trying to reduce error for negative x in an exponential function

I am using the Taylor series expansion to estimate e^x. I have written a program that does this and it works well for big values of n. However, I'm not happy with the fact that for negative values of x the error increases for a significant amount of time before reducing.
I would like to make it work equally well for x>0 and x<0 and I'm sure it can be done I just can't see what I'd need to change and whats going wrong.
Here's my code:
function T = findexp(x,n) %findexp, function to evaluate e^x for some value of n, we will use n = 100
% Initialise the vector e used for the error function e=zeros(1,n);
% Set initial conditions, T(0) is an invalid argument so we use T(1) T(1)=1; e(1)=abs(T(1)-exp(x))/x;
% Recursive formula that calculates T(i) and e(i) for i = 2:n+1 T(i) = T(i-1)+x^(i-1)/(factorial(i-1)); e(i) = abs((T(i)-exp(x))/(x));
% On the last loop we print the calculated value of e^x
if i == n+1
fprintf(1,'T(%d) = %1.15e\n',x,T(i));
end
end
% Plot the error on a log-log graph p=1:1:n+1; y=e(p); plot(log10(p),log10(y))
P.S. on a side note should I be using log10 or log for a log-log plot?
THanks in advance,
Harry

1 comentario

See http://www.mathworks.com/matlabcentral/answers/7885-tutorial-how-to-format-your-question for how to format your code.

Iniciar sesión para comentar.

Respuestas (1)

Andrew Newell
Andrew Newell el 20 de En. de 2012
Using a Taylor series to calculate exp(x) for negative x is a bad idea because rounding errors quickly destroy the accuracy. There is a simple fix, though: if x is negative, calculate exp(abs(x)) and then take the reciprocal!

Categorías

Más información sobre Mathematics en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 20 de En. de 2012

Community Treasure Hunt

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

Start Hunting!

Translated by