c++ fmod returns 0.2 for fmod(0.6,0.2)

后端 未结 3 614
执念已碎
执念已碎 2021-01-23 06:00

when I use fmod(0.6,0.2) in c++ it returns 0.2

I know this is caused by floating point accuracy but it seems I have to get remainder of two double this moment

th

3条回答
  •  梦毁少年i
    2021-01-23 06:23

    The mathematical values 0.6 and 0.2 cannot be represented exactly in binary floating-point.

    This demo program will show you what's going on:

    #include 
    #include 
    #include 
    int main() {
        const double x = 0.6;
        const double y = 0.2;
        std::cout << std::setprecision(60)
                  << "x          = " << x << "\n"
                  << "y          = " << y << "\n"
                  << "fmod(x, y) = " << fmod(x, y) << "\n";
    }
    

    The output on my system (and very likely on yours) is:

    x          = 0.59999999999999997779553950749686919152736663818359375
    y          = 0.200000000000000011102230246251565404236316680908203125
    fmod(x, y) = 0.1999999999999999555910790149937383830547332763671875
    

    The result returned by fmod() is correct given the arguments you passed it.

    If you need some other result (I presume you were expecting 0.0), you'll have to do something different. There are a number of possibilities. You can check whether the result differs from 0.2 by some very small amount, or perhaps you can do the computation using integer arithmetic (if, for example, all the numbers you're dealing with are multiples of 0.1 or of 0.01).

提交回复
热议问题