# e vs exp()?

Bengt Richter bokr at oz.net
Thu Sep 26 19:55:52 EDT 2002

```On Thu, 19 Sep 2002 21:51:25 -0700, "James J. Besemer" <jb at cascade-sys.com> wrote:

>
>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
>>
>>
>>>>>from math import *
>>>>>e**2
>>>>>
>>>>>
>>7.3890560989306522
>>
>>
>>>>>exp(2)
>>>>>
>>>>>
>>7.3890560989306504
>>
>>
>Mathematica says e**2 to 30 digits is:
>
>    7.3890560989306502 272304274606
>
We can also brute force the series for e with longs and maybe ignore the last few digits:

>>> def calce(nd):
...     numi = n = 10L**nd
...     deni = 1L
...     i = 0; s = ''
...     while 1:
...         i += 1
...         numi = numi*i + n
...         deni *= i
...         sl, s = s, str(numi/deni)
...         if sl[:nd+1] == s[:nd+1]: return numi, deni
...
>>> n,d = calce(60)
>>> n/d
2718281828459045235360287471352662497757247093699959574966967L
>>> (n/d)**2
7389056098930650227230427460575007813180315570551847324087124...
Comparing side by side:
7.3890560989306502 27230427460575007813180315570551847324087124...
vs
7.3890560989306502 272304274606 from matlab
7.3890560989306522              for e**2, and
7.3890560989306504              for exp(2)

The latter seems more accurate.

>in which case the second form would happen to be more accurate.
>
>Since Python math uses your machine's native floating point formats,
>precision is necessarily limited and one should not be surprised to
>encounter minor errors in the least significant bits or digits.
>
>Although Mathematica recognizes that the two forms are identical, Python
>uses different formula for computing the two results.  The fact that the
>base is "e" is of no consequence to the computation.  exp() is computed
>from C's exp() runtime library routine, whereas e**2 is evaluated using
>C's "pow()" function.
>
>In general, I would expect pow() to be less accurate, as pow(x,y)
>probably is computed by exp(log(x)*y).
>
Looks plausible.

Regards,
Bengt Richter

```