I have to write a function in Octave which is computing e^x. I wrote this:
function y=f(x)
y=0; t=1; k=1;
while abs(t)>0.001
y=y+t;
t=t*(x/(2*k));
k=k+1;
end
y=y^2;
end;
Everything is okay when I'm computing $f(20)$ or $f(-30)$ etc. But when I try to compute $f(-2000)$ I should get $ \approx 0$, but Octave says it's $\infty$. Is it my fault (I mean something's wrong with code)?
In the spirit of arbautjc's comment, given the operators you have, you can always ensure that the magnitude of the argument is less than $1$. Furthermore if $x<0$, you can do as vonbrand suggested and use index laws to aid your calculations. This will likely be much slower than simply using the
exp(..)command built in.The following is MATLAB code, but it should work in Octave as well.
Some results are below.
Vis value andTis execution time.tolwas set to1e-6.