Comparing floats

Discussion in 'C++' started by saneman, Aug 19, 2008.

  1. saneman

    saneman Guest

    I have a function:

    int F(double a)
    if (a = =1.0)
    return 22;
    return 44;

    When I call F(1.0) it returns 22. But if I call F from a loop like:

    double a = 0.0;
    for (int j = 0; j <= 1000; j++)
    std::cout << F(a) <<std::endl;
    a = a + 0.001;

    It returns 44 instead when 'a' reaches 1 instead of 22!

    After a few hours of messing with my brains I found a website where they say
    that comparing floats in C++ is not guranteed to return an expected result.
    Instead something like this should be used:

    if (fabs(result - expectedResult) < 0.00001)

    But before I rewrite all my code that compare floats I would like to hear if
    anyone has any better suggestion.
    saneman, Aug 19, 2008
    1. Advertisements

  2. It depends on what you want to do. Most times it is wrong as well. But
    this isn't C++ specific; for starters, study the paper "What Every
    Computer Scientist Should Know About Floating-Point Arithmetic", by
    David Goldberg.
    Gennaro Prota, Aug 19, 2008
    1. Advertisements

  3. saneman

    saneman Guest

    This is because:

    I have tried doing std::cout << a << std::endl; but it just prints the
    numbers from 0.001 to 1 as expected.
    saneman, Aug 19, 2008
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.