声明两个浮点数相等

时间:2019-02-26 21:41:50

标签: python floating-point assert

以下代码在最后一行给出了AssertionError。 但是,两个值都打印为10.0833333333

p = [0,1,2,3,4,6,2,2,4,1,2,4]
cell11 = p[0:3]
cell12 = p[3:6]
cell21 = p[6:9]
cell22 = p[9:12]

x11 = sum(cell11)/float(3)
x12 = sum(cell12)/float(3)
x21 = sum(cell21)/float(3)
x22 = sum(cell22)/float(3)
x1dot = (x11+x12)/float(2)
x2dot = (x21+x22)/float(2)
xdot1 = (x11+x21)/float(2)
xdot2 = (x12+x22)/float(2)
xdotdot = (x1dot+x2dot)/float(2)
assert(xdotdot == (xdot1+xdot2)/float(2))
n=3
x11diff = ((x11-xdotdot) - (x1dot-xdotdot) - (xdot1-xdotdot))**2
x12diff = ((x12-xdotdot) - (x1dot-xdotdot) - (xdot2-xdotdot))**2
x21diff = ((x21-xdotdot) - (x2dot-xdotdot) - (xdot1-xdotdot))**2
x22diff = ((x22-xdotdot) - (x2dot-xdotdot) - (xdot2-xdotdot))**2
ssaxb = n*(x11diff+x12diff+x21diff+x22diff)
print str(ssaxb)
print str(10+(1/float(12)))
assert(ssaxb == 10+(1/float(12)))

ssaxb10+(1/float(12))是否以某种方式存储为略有不同的值?

1 个答案:

答案 0 :(得分:-1)

@Chris_Rands指出,打印值将为您提供断言语句失败的原因,因为浮点值不同

import numpy as np

print(ssaxb, 10+(1/float(12)))  #(10.08333333333333, 10.083333333333334)

assert(np.isclose(ssaxb, 10+(1/float(12))))

assert(round(ssaxb,7),round(10+(1/float(12)),7))