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?
C exp() The exp() function computes e (2.71828) raised to the power of the given argument.
The exp() function in C++ returns the exponential (Euler's number) e (or 2.71828) raised to the given argument. Syntax for returning exponential e: result=exp() Parameter: The function can take any value i.e, positive, negative or zero in its parameter and returns result in int, double or float or long double.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With