[Python-ideas] Floating point "closeness" Proposal Outline
Steven D'Aprano
steve at pearwood.info
Wed Jan 21 12:59:34 CET 2015
On Wed, Jan 21, 2015 at 09:27:39AM -0200, Joao S. O. Bueno wrote:
> 1) Implement a Number class that behaves as a float number, and does
> the fuzzy comparisons automatically.
-1 on this.
> Justificative: in a whole lot of code, having a "casted"
> FuzzyFloat(mynumber) to be able to be compared to others with "==" and "<="
> would be much more readable than the Javaesque
>
> " if is_close(my_number, other) or my_number < other: "
> (against:
> "if FuzzyFloat(my_number) <= other :"
> , or simply
>
> "if my_number <= other: "
If that sort of comparison is important, a helper function is easy to
write. But it really sounds like you want a full interval arithmetic
class, which is a lot more than just fuzzy comparisons.
There are two problems with overriding == in this way:
(1) What do you mean by "is close"? Do you mean that they are within
0.0001 or 0.00000001 or within 10000.0? With a binary operator == there
is no easy way to specify an error tolerance, which means you're stuck
with using a language-wide default which is very unlikely to be suitable
for your application. A context manager is one solution, but that's
still awkward. Think about doing:
a == b or x == y
where the a, b comparison and x, y comparison have different tolerances.
(2) Fuzzy equality means that there are situations where:
a == b and b == c
but
a != c
The language APL tried to turn this into a feature:
The intransitivity of [tolerant] equality is well known in practical
situations and can be easily demonstrated by sawing several pieces
of wood of equal length. In one case, use the first piece to measure
subsequent lengths; in the second case, use the last piece cut to
measure the next. Compare the lengths of the two final pieces.
— Richard Lathwell, APL Comparison Tolerance, APL76, 1976
but I'm not so sure. If we introduced a new comparison operator (perhaps
the Unicode symbol ≈ or the ASCII ~= ?) I'd be less concerned but I
think overriding == for fuzzy equality is a mistake.
--
Steve
More information about the Python-ideas
mailing list