Cancellation in the exponential function

311 Views Asked by At

I have the following issue about numerical analysis:

enter image description here

Well, part a) is the one I did, in the following code in Octave

function val=miexp(x)
ep=10^(-15);
val=1.0; n=1; e0=0;
do
e0=val;
val+=(x)^(n)/factorial(n);
n++;
until(abs(val-e0)<=ep)
endfunction

For b) the criterion is to stop when the difference is very small. In c) the comparison of the results goes very well to the approximations. In d)I think it is not necessary because my code calculates for values of x <0, and therefore in e) I don't know what to do either. I don't know what I did wrong in my code, because I understand the purpose of the problem, which is to show the weakness of the floating point arithmetic, since at a certain point there are going to be cancellations, so I don't know what the problem of my implementation is.

I would appreciate any help in advance, regards.

Edit: for $x<0$

if x<0
  do
  aux1=pos;
  pos+=(x)^(2*n)/factorial(2*n);
  n++;
  until(abs(pos-aux1)<=ep)
  do
  aux2=neg;
  neg+=(x)^(2*m+1)/factorial(2*m+1);
  m++;
  until(abs(neg-aux2)<=ep)
  val=pos+neg;
else
1

There are 1 best solutions below

5
On BEST ANSWER

For $x < 0$, As $x$ gets smaller, you would have a bunch of cancellation errors due to the alternating addition and subtraction. For $x > 0$ there is only addition so you avoid those.

A hint is given to you that $e^{-x} = \frac{1}{e^x}$

You can avoid cancellation errors for $e^{-x}$ by instead calculating $e^x$ and performing one final calculation $\frac{1}{e^x}$ when your tolerance is matched