e vs exp()?
Fernando Pérez
fperez528 at yahoo.com
Fri Sep 20 13:23:01 EDT 2002
Buckshot wrote:
> Can anyone here explain why I'm getting different results from
> e**2 and exp(2)? Which is more accurate?
>
> Python 2.2 (#1, Mar 27 2002, 14:56:58)
> [GCC 2.95.3 20010315 (release)] on sunos5
> Type "help", "copyright", "credits" or "license" for more information.
>>>> from math import *
>>>> e**2
> 7.3890560989306522
>>>> exp(2)
> 7.3890560989306504
As someone already told you, exp(2) gives a more accurate answer. The reason
is, I think, the following: e**2 simply squares e, and this amplifies the
error in the value for e (which is stored at finite precision, as a C double
inside). OTOH, exp(2) computes e**2 to a given accuracy, so it will not be
propagating the finite-precision error inherent in the 'e' value. As long as
the exp() function is correctly implemented in the system's math library, it
should be more accurate than hand-calculations done with 'e'. In most cases
the difference shouldn't matter, but if you are doing something very
sensitive to numerical roundoff or require delicately balancing
cancellations, you may need to pay attention to this.
Cheers,
f.
More information about the Python-list
mailing list