kst*_*tis 3 python floating-point floating-accuracy python-2.6 python-2.7
所以我打破了Python 2.6解释器,我得到了这个:
Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2.1
2.1000000000000001
>>> 2.2
2.2000000000000002
>>> 2.2
2.2000000000000002
Run Code Online (Sandbox Code Playgroud)
但是在Python 2.7中,我得到了更像人类的结果,如下所示:
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 5.4
5.4
>>> 1.1
1.1
>>> 0.2
0.2
>>>
Run Code Online (Sandbox Code Playgroud)
我想问为什么会发生这种情况,我怎么可能让Python 2.6表现得像2.7?
Mar*_*ers 10
Python 2.7中的float.__repr__()和float.__str__()方法发生了变化; Python 3.1 float-to-string转换方法被反向移植,现在值已四舍五入.
C源代码,float.__str__()使用g格式化程序代码为sprintf()函数格式化浮点值,精度为12个位置.
要在Python 2.6中获得相同的结果,您必须自己格式化字符串:
'%.12g' % fp_value
Run Code Online (Sandbox Code Playgroud)
或使用format()功能:
format(fp_value, '.12g')
Run Code Online (Sandbox Code Playgroud)
请注意,在Python 2.7中,仅更改了表示,而不是实际值.浮点值仍然是实数的二进制近似值,二进制分数并不总是加起来表示的确切数字.
如果您需要比float近似值提供的精度更高,则需要切换到使用该decimal.Decimal()类型.这样可以以速度为代价保持精度(浮点运算在现代计算机上的硬件中处理).