Comparing floats

kj no.email at please.post
Sat Nov 27 17:55:10 EST 2010




I'm defining a class (Spam) of objects that are characterized by
three parameters, A, B, C, where A and C are n-tuples of floats
and B is an n*n tuple-of-tuples of floats.  I'm defining a limited
multiplication for these objects, like this:

Spam(A, B, C) * Spam(D, E, F) = Spam(A, dot(B, E), F)
  if and only if C == D.

(Here dot(B, E) represents the matrix multiplication of B and E).

In other words, this multiplication is defined only for the case
where the last parameter of the first object is equal to first
parameter of the second object.  An exception should be thrown if
one attempts to multiply two objects that fail to meet this
requirement.

Therefore, to implement this multiplication operation I need to
have a way to verify that the float tuples C and D are "equal".
Certainly, I want to do this in in a way that takes into account
the fact machine computations with floats can produce small
differences between numbers that are notionally the same.  E.g.
(in Python 2.6.1 at least):

>>> 49.0 * (1.0/49.0)
0.99999999999999989
>>> 1.0 == 49.0 * (1.0/49.0)
False

The only approach I know of is to pick some arbitrary tolerance
epsilon (e.g. 1e-6) and declare floats x and y equal iff the absolute
value of x - y is less than epsilon.

Does the Python standard library provide any better methods for
performing such comparisons?

I understand that, in Python 2.7 and 3.x >= 3.1, when the interactive
shell displays a float it shows "the shortest decimal fraction that
rounds correctly back to the true binary value".  Is there a way
to access this rounding functionality from code that must be able
to run under version 2.6? (The idea would be to implement float
comparison as a comparison of the rounded versions of floats.)

Absent these possibilities, does Python provide any standard value
of epsilon for this purpose?

TIA!

~kj



More information about the Python-list mailing list