0

So whenever I sum an array of floating numbers, and compare the summed number with another floating number it keeps saying they are not the same.

So the total is 1.63 The numbers are: 0.31, 0.31, 0.37, 0.33, 0.31

These numbers together makes 1.63, but whenever I compare the sum with 1.63 it says they are not the same.

How come this happens?

#!/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

result:

1.63
1.63
not ok
1.63 1.63
p0nts
  • 63
  • 2
  • 12
  • also, good read: https://docs.python.org/3/tutorial/floatingpoint.html – Paritosh Singh Jun 18 '19 at 07:59
  • thanks, that looks like it is what I already thought, I was already experimenting with "{:.{prec}f}" because the numbers I use always have the same amount of decimals. – p0nts Jun 18 '19 at 08:02
  • for that, https://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python – Paritosh Singh Jun 18 '19 at 08:03

1 Answers1

1
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
qaiser
  • 2,770
  • 2
  • 17
  • 29