1

I can't understand why this code returns False:

list_of_disks = [[170, 158, 470, 0.1], [135, 176, 410, 0.2], [100, 193, 350, 0.3], [170, 458, 470,       1.1]]
def f1(pos):
    for x in range(0, len(list_of_disks)):
        if list_of_disks[x][3] == pos:
            print list_of_disks[x+1][3] - 0.1, list_of_disks[x][3]
            print list_of_disks[x+1][3] - 0.1 == list_of_disks[x][3] # Why is this False..?
            break

f1(0.2)

When I print out the 2 values, they seem to be the same..? Hope someone can help me out here, thanks!

Mark
  • 105
  • 1
  • 3
  • 8

1 Answers1

1

This is because 0.1 cannot be stored by computers (there is no exact binary representation of it), so 0.3-0.1 is not the same as 0.2 to python:

>>> 0.3-0.1==0.2
False

See http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/ for mor details on floating point precision.

You can avoid those pitfalls by using the Decimal module, an implementation of exact decimal floating point arithmetic.

The purpose of this module is to support arithmetic using familiar
"schoolhouse" rules and to avoid some of the tricky representation
issues associated with binary floating point.  The package is especially
useful for financial applications or for contexts where users have
expectations that are at odds with binary floating point (for instance,
in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected
Decimal('0.00')).
ch3ka
  • 11,792
  • 4
  • 31
  • 28