Search code examples
pythonstringpython-2.7floating-pointrepr

How does Python determine whether to represent a number using scientific notation or not?


Here are some numbers entered in the Python console, and the resulting representations:

>>> 1
1
>>> 1.234
1.234
>>> 1.234e5
123400.0
>>> 1.234e15
1234000000000000.0
>>> 1.234e25
1.234e+25

... and here's what happens when the same numbers are printed:

>>> print 1
1
>>> print 1.234
1.234
>>> print 1.234e5
123400.0
>>> print 1.234e15
1.234e+15  # different!
>>> print 1.234e25
1.234e+25

How does Python decide which representation to use? Why is it different with and without print for some numbers?


Solution

  • Only floating point numbers are represented using scientific notation in Python; integers are always represented as-is.

    How a floating point number is represented in Python 2.7 depends on whether it's represented using repr() (for instance, directly in the console or as a member of a collection) or str() (e.g. with the print statement).

    With repr(), floating point numbers are represented using scientific notation if they are either less than 0.0001 (1e-4) or at least 1e16:

    >>> 1e-4
    0.0001
    >>> 0.00009999
    9.999e-05
    >>> 1e16-2
    9999999999999998.0
    >>> 10000000000000000.0
    1e+16
    

    With str(), the upper limit is approximately 1e11:

    >>> print 1e11-1
    99999999999.0
    >>> print 100000000000.0
    1e+11
    

    Note: in Python 3, str() now represents floating point numbers in the same way as repr().