Re: Float comparison



Mark McIntyre <markmcintyre@xxxxxxxxxxxxxxxxxxx> writes:

On 21/04/09 21:38, Eric Sosman wrote:
Mark McIntyre wrote:
On 21/04/09 11:18, Alessio Ribeca wrote:

Thank you, How can I check for [floating-point] equality ?

You can't. You can only see if two floats are very close to each other.

This bit of nonsense has cropped up more than once in this
thread, so I'm very much afraid people may believe it. But it's
still nonsense!

I disagree.
<snip>
But strict equality *is* testable in C, if you want to do it,
and don't listen to anyone who tries to tell you otherwise.

And don't listen to anyone who tells you its safe to use == to compare
floats. Really Eric, I'm shocked. Is this you, or a sockpuppet.

I disagree. Ages ago (I say this only to excuse the inevitable errors
that my memory will introduce) I wrote a package for doing interval
arithmetic. A number like 0.1 would be represented by the smallest
representable interval that contains 0.1.

Sometimes the user knows an input number is both perfectly accurate
and representable (for example the power in the inverse square law can
be taken to be 2). There was a notation for this (I forget) that
created an interval of zero width. The arithmetic algorithms were
much faster if this case was given special treatment (usually you need
half the number of operations) which of course was done with an
equality test.

This anchored a couple of things firmly in my mind: that == is
sometimes what you want to test floating point numbers for, and that
floats are exact. There was no error in the end points of the
intervals. They were exact values even though, in most cases, neither
was an entirely accurate representation of the value the programmer
wanted.

--
Ben.
.



Relevant Pages

  • Re: RAD vs. performance
    ... ints and floats into account. ... Floats are but one representation of numbers. ... dynamically typed language, you could just feed the above code through ... compiler would reject the program. ...
    (comp.lang.misc)
  • Re: Why cant I xor strings?
    ... It converts a number to an ordered set of bools, ... > possible states of the representation machinery. ... *much* less well equipped to handle the way floats bite you than someone ...
    (comp.lang.python)
  • Re: Why cant I xor strings?
    ... > IMO we have implicit subtyping of integers as vectors or column matrices ... > of bools and operations element by element and implicit re-presentation ... Abstractly, even floats have a binary representation, just as they ...
    (comp.lang.python)
  • Re: How to truncate/round-off decimal numbers?
    ... this is just a matter of representation. ... If we use floats with two decimals ... And multiplying, ...
    (comp.lang.python)
  • Re: Floating point bug?
    ... "never test floats for equality". ... [end quote] ... you often do want to test floating point values within some ...
    (comp.lang.python)