c++square-rootexp

Something really weird with C++ exp() function


When tying to implement mySqrt function in C++, I used the exp() function like this:

int mySqrt(int x) {
    // For x = 2147395600
    cout << exp(0.5*log(x)) << "  ";     // It prints 46340
    return exp(0.5*log(x));              // But returns 46339
}

I tried to google the reason for this behavior but could not find anything. I even tried using double but still the same output.

Any explanation for this?


Solution

  • With this code

    #include <iostream>
    #include <cmath>
    #include <cstdio>
    using std::cout;
    
    int mySqrt(int x) {
        // For x = 2147395600
        cout << exp(0.5*log(x)) << "  ";     // It prints 46340
        return exp(0.5*log(x));              // But returns 46349
    }
    
    int main(void) {
        std::cout << mySqrt(2147395600) << "\n";
        printf("%.30f\n", exp(0.5*log(2147395600)));
        return 0;
    }
    

    I got output:

    46340  46339
    46339.999999999978172127157449722290
    

    It seems the value is rounded when passed to cout while truncated when converted to int.