[Tutor] Exponential function

eryk sun eryksun at gmail.com
Tue Feb 14 23:43:22 EST 2017


On Tue, Feb 14, 2017 at 11:01 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
> To compute it if you don't know x in advance then yes,
> use something like
>
> value = 10**x
>
> But if you know the value in advance you can write it in
> a more compact form as:
>
> value = 1e5  # or 3e7 or whatever...

10**5 is an int and 1e5 is a float. This could lead to a significant
loss of precision depending on the calculation. For example:

    >>> x = 10**5 * 1234567890123456789
    >>> y = 1e5 * 1234567890123456789
    >>> x - y
    16777216.0

Replacing 10**5 with 100000 is a compile-time optimization (constant
expression folding), so you needn't worry about manually optimizing
it. For example:

    >>> compile('10**5', '', 'exec').co_consts
    (10, 5, None, 100000)

The compiled bytecode refers to the pre-computed constant:

    >>> dis.dis(compile('10**5', '', 'exec'))
      1           0 LOAD_CONST               3 (100000)
                  3 POP_TOP
                  4 LOAD_CONST               2 (None)
                  7 RETURN_VALUE


More information about the Tutor mailing list