hug*_*o24 1 python random floating-point-precision
在Python 2.6和Python 2.7中使用Random.random()时,为什么会有不同的精度
例:
import random
import sys
rng = random.Random(0)
print sys.version
for i in range(10):
print repr(rng.random())
Run Code Online (Sandbox Code Playgroud)
2.6.6(r266:84297,2010年8月24日,18:46:32)[MSC v.1500 32 bit(Intel)]
0.84442185152504812
0.75795440294030247
0.4205715808308452.7.5(默认,2013年5月15日,
22:
43:
36 )[MSC v.1500 32 bit(Intel)] 0.8444218515250481 0.7579544029403025 0.420571580830845
为什么有不同的精度?可能是因为这种变化:http: //docs.python.org/2/tutorial/floatingpoint.html#representation-error
在Python 2.7和Python 3.1之前的版本中,Python将此值四舍五入为17位有效数字,给出"0.10000000000000001".在当前版本中,Python显示一个基于最小小数的值,该小数正确地回滚到真正的二进制值,结果只是'0.1'.
返回的数字random()是相同的.它的显示精度是不同的.
这是我的Python 2.7返回的前两个数字,但显示的默认值更多十进制数字:
$ python
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> rng = random.Random(0)
>>> '%.50f' % rng.random()
'0.84442185152504811718188193481182679533958435058594'
>>> '%.50f' % rng.random()
'0.75795440294030247407874867349164560437202453613281'
Run Code Online (Sandbox Code Playgroud)
如果将这些数字舍入到17位小数,那么您将获得与从Python 2.6获得的数字完全相同的数字.