双精度和浮点精度
Double and Float Precision
a = 2.3
b = a*100
print b
输出:230.0
print 2.3*100
输出:229.99999999999997
Double 和 Float 乘法的执行方式似乎有所不同。是吗?
上述行为的解释是什么?
首先,Python浮点数只有一种类型,即float;没有double类型。
现在,我不确定为什么,但您的问题似乎归结为使用 print
。
>>> 2.3*100
229.99999999999997
>>> print 2.3*100
230.0
那是 Python 2.7.10。有趣的是,这在 3.5.1 中没有发生:
>>> 2.3*100
229.99999999999997
>>> print(2.3*100)
229.99999999999997
快速 google 搜索给了我 this.
基本上,浮点数以位 (0-1) 表示,类似于我们知道的数字用 0-9 表示的方式。很多数字不能这样准确表示,类似于我们不能准确表示十进制的 1/3(常规 0-9)。
我假设您使用旧的 python 2 因为您的 print
声明。当我 运行 您提供的代码时,对于两个 print
语句,我得到相同的结果:
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
>>> a = 2.3
>>> b = a*100
>>> print b
230.0
>>> print 2.3*100
230.0
我怀疑您正在使用交互式 python。这是浮点数转字符串的特性:
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
>>> 2.3*100
229.99999999999997
>>> print 2.3*100
230.0
>>> str(2.3*100)
'230.0'
>>> repr(2.3*100)
'229.99999999999997'
这说明了 print
使用的 str
和交互式 python 使用的 repr
之间的区别。
a = 2.3
b = a*100
print b
输出:230.0
print 2.3*100
输出:229.99999999999997
Double 和 Float 乘法的执行方式似乎有所不同。是吗?
上述行为的解释是什么?
首先,Python浮点数只有一种类型,即float;没有double类型。
现在,我不确定为什么,但您的问题似乎归结为使用 print
。
>>> 2.3*100
229.99999999999997
>>> print 2.3*100
230.0
那是 Python 2.7.10。有趣的是,这在 3.5.1 中没有发生:
>>> 2.3*100
229.99999999999997
>>> print(2.3*100)
229.99999999999997
快速 google 搜索给了我 this.
基本上,浮点数以位 (0-1) 表示,类似于我们知道的数字用 0-9 表示的方式。很多数字不能这样准确表示,类似于我们不能准确表示十进制的 1/3(常规 0-9)。
我假设您使用旧的 python 2 因为您的 print
声明。当我 运行 您提供的代码时,对于两个 print
语句,我得到相同的结果:
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
>>> a = 2.3
>>> b = a*100
>>> print b
230.0
>>> print 2.3*100
230.0
我怀疑您正在使用交互式 python。这是浮点数转字符串的特性:
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
>>> 2.3*100
229.99999999999997
>>> print 2.3*100
230.0
>>> str(2.3*100)
'230.0'
>>> repr(2.3*100)
'229.99999999999997'
这说明了 print
使用的 str
和交互式 python 使用的 repr
之间的区别。