Boost logo

Boost Users :

Subject: Re: [Boost-users] [lexical_cast] float-to-string rounding error (notfound with cout)
From: Dominique Devienne (ddevienne_at_[hidden])
Date: 2009-04-30 15:57:07


On Thu, Apr 30, 2009 at 2:33 PM, OvermindDL1 <overminddl1_at_[hidden]> wrote:
>
> It might help to read up on the IEEE floating point standards.

[DD] Wikipedia has a decent overview.

> This is also why you *NEVER* (and this is important enough to say
> again, ***NEVER***) directly compare floats for equality, there can be
> arbitrary accuracy in the number.

[DD] Rarely, not never ;-)

> Example:
> bool FloatsEqual(float f1, float f2)
> {
>    return f1=f2;
> }
>
> A more proper implementation would be:
> bool FloatsEqual(float f1, float f2, float eps=0.00001)
> {
>    return eps>(f1-f2);
> }

I'm no expert, but the above does not take into account the
"magnitude" of the numbers.
Comparing 0.000001 and 0.0000011 with 0.000001
and 999999.0 and 999999.1 with 0.00001 don't mean the same thing at all.

By dividing with the sum (when non-null), e then represents the
"significant digits" fuzzy compare.

    if( (x + y) != 0 ) {
        return tiny( (x - y) / (x + y), e);
    } else {
        // x == -y
        return tiny( x, e );
    }

inline bool tiny(float x, float e) { // and double overload
    return abs(x) <= e; // abs if our abs
}

But again, I'm no numerical expert. I'm sure someone will correct the
above ;-) --DD


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net