使用numpy.float32
。Python float vs numpy.float32
t = numpy.float32(.3)
x = numpy.float32(1)
r = numpy.float32(-.3)
_t = t+x+r
_t == 1 # -> False
使用常规Python float
。
t = .3
x = 1
r = -.3
_t = t+x+r
_t == 1 # -> True
为什么?
使用numpy.float32
。Python float vs numpy.float32
t = numpy.float32(.3)
x = numpy.float32(1)
r = numpy.float32(-.3)
_t = t+x+r
_t == 1 # -> False
使用常规Python float
。
t = .3
x = 1
r = -.3
_t = t+x+r
_t == 1 # -> True
为什么?
浮点值在计算机上本质上是不准确的。根据https://docs.python.org/2/tutorial/floatingpoint.html,python默认的float
是大多数机器上所谓的双精度浮点数。 numpy.float32
是一个单精度浮点数。这是双精度对手是numpy.float64
。这可以解释这种情况下的差异。
通常不应使用==
直接比较浮点数。您可以使用numpy.isclose
来处理由非精确浮点表示造成的小错误。
的Python浮子是C双键类型:documentation:
浮点数在下使用双通常被实现;有关运行程序的机器的浮点数的精度和内部表示的信息可在
sys.float_info
中找到。
因此,您正在比较32位和64位精度浮点数。下面的工作:
t = numpy.float64(.3)
x = numpy.float64(1)
r = numpy.float64(-.3)
_t = t+x+r
_t == 1
https://docs.python.org/2/tutorial/floatingpoint.html –
你并不需要做一个'np.float32'直接对象。制作一个多项目数组。 – hpaulj