Trying to reduce error for negative x in an exponential function
Afficher commentaires plus anciens
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 commentaire
Andrew Newell
le 20 Jan 2012
See http://www.mathworks.com/matlabcentral/answers/7885-tutorial-how-to-format-your-question for how to format your code.
Réponses (1)
Andrew Newell
le 20 Jan 2012
1 vote
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!
Catégories
En savoir plus sur Mathematics dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!