求和数字并在失败后比较浮点数



因此,每当我对浮点数数组求和,并将求和的数字与另一个浮点数进行比较时,它总是说它们不一样。

所以总数是 1.63这些数字是:

0.31、0.31、0.37、0.33、0.31

这些数字加起来就是1.63,但是每当我将总和与1.63进行比较时,它就会说它们不一样。

怎么会这样呢?

#!/usr/bin/python
total = 1.63
array = [ 0.31, 0.31, 0.37, 0.33, 0.31 ]
sum = 0
for n in array:
  sum += float(n)
print total
print sum
if float(total) == float(sum):
  print 'ok'
else:
  print 'not ok'
  print total, sum

结果:

1.63
1.63
not ok
1.63 1.63
array = [ 0.31, 0.31, 0.37, 0.33, 0.31 ]
print(sum(array))
#o/p = 1.6300000000000001
# you need to round off upto 2 decimal place to make it equal with 1.63
round(sum(array),2) 
#o/p
1.63

最新更新