1

Im using fmod() in one of my programs, and it is producing unexpected results, can anyone help me with this?

this is the code:

int main(int argc, char** argv)
{
    double test = 0.756;

    while (fmod(test, 1) != 0)
    {
        test = test * 10;
        std::cout << test << " " << fmod(test, 1) << std::endl;
    }
    std::cout << "Final Product: " << test;

    getchar();
    return 0;
}

and this is the output:

7.56 0.56
75.6 0.6
756 1.13687e-13
7560 9.09495e-13
...
Final Product: 7.56e+15

Why does fmod(756, 1) == 1.13687e-13? Shouldn't fmod(756, 1) == 0?

  • 2
    Nope! Generally speaking, you should never try to get exact results out of floating point calculations. –  Sep 21 '15 at 01:22
  • @Hurkyl I assumed this was because of floating point precision. Thanks! –  Sep 21 '15 at 01:23
  • 1
    There may be a guarantee about `fmod(756,1)` (I'm not sure on that fine of detail) but I additionally think it's likely that the number printed as `756` is not actually equal to `756.0`. I bet you'd see a difference if you changed the precision of the printing. –  Sep 21 '15 at 01:25
  • @Hurkyl Your right, i just stepped through it, and found the value was actually 756.00000000000011. That solves my problem, thanks for the help –  Sep 21 '15 at 01:27

0 Answers0