简体   繁体   中英

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?

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() (eg 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() .

Numeric values are just stored as values. The __repr__ output may change based on the implementation and type of number. You need to format the string representation of a number.

Example:

>>> type(1e3) is type(1000.0) # float
True
>>> type(1e3) is type(1000)  # int
False

When you format a string, you can use %g / {:g} to have it automatically determine the most readable format. Use %e / {:e} for explicit scientific notation.

>>> x = 1234567
>>> "{:.2e}".format(x)
1.23e+06

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM