MATLAB: [HELP] A Classical Numerical Computing Question

matlab operationsnumerical computing

f(x) = (exp(x)-1)/x; g(x) = (exp(x)-1)/log(exp(x))
Analytically, f(x) = g(x).
When x is approaching to 0, both f(x) and g(x) are approaching to 1. However, g(x) works better than f(x).
% Compute y against x
for k = 1:15
x(k) = 10^(-k);
f(k) =(exp(x(k))-1)/x(k);
De(k) = log(exp(x(k)));
g(k)= (exp(x(k))-1)/De(k);
end
% Plot y
plot(1:15,f,'r',1:15,g,'b');
f(x) actually diverges when x approaches to 0.But shouldn't them be the same??

Best Answer

No, they shouldn't be the same at the fringes. This is an example of why we often have to look for more stable ways of doing in floating point arithmetic what is analytically simple. Look how f oscillates:
f = @(x) (exp(x)-1)./x;
g = @(x) (exp(x)-1)./log(exp(x));
x = 0:1e-13:1e-7; % Try with x = 0:2e-14:1e-7;
ax(1) = subplot(1,2,1);
plot(x,f(x),'r')
title('(exp(x)-1)./x')
ax(2) = subplot(1,2,2);
plot(x,g(x),'b');
title('(exp(x)-1)./log(exp(x))')
L = get(gca,{'xlim','ylim'});
axis(ax(1),[L{:}])
Related Question