简体   繁体   English

Python如何确定是否使用科学计数法表示数字?

[英]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: 以下是在Python控制台中输入的一些数字及其结果表示形式:

>>> 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? Python如何决定要使用哪种表示形式? Why is it different with and without print for some numbers? 为什么某些数字有无print会有所不同?

Only floating point numbers are represented using scientific notation in Python; 在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). 如何在Python 2.7中表示浮点数取决于它是使用repr() (例如,直接在控制台中还是作为集合的成员)还是str() (例如,使用print语句)表示的。

With repr() , floating point numbers are represented using scientific notation if they are either less than 0.0001 ( 1e-4 ) or at least 1e16 : 使用repr() ,如果浮点数小于0.00011e-4 )或至少为1e16 ,则使用科学计数法表示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 : 使用str() ,上限大约为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() . 注意:在Python 3中, str()现在以与repr()相同的方式表示浮点数。

Numeric values are just stored as values. 数字值只是存储为值。 The __repr__ output may change based on the implementation and type of number. __repr__输出可能会根据数字的实现和类型而改变。 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. 格式化字符串时,可以使用%g / {:g}使其自动确定最易读的格式。 Use %e / {:e} for explicit scientific notation. 使用%e / {:e}表示明确的科学符号。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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