5

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?

Rakshak
  • 73
  • 6

1 Answers1

6

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.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • 3
    Converting a floating point value (e.g. `double`) to an integral type (like `int`) rounds toward zero. That is one of the basic conversions specified in the standard. – Peter May 09 '20 at 07:42
  • 3
    @Rakshak If you wonder about the result of `46339.999999999978172127157449722290` then this might be worth to read: [What Every Programmer Should Know About Floating-Point Arithmetic](http://floating-point-gui.de/). ;-) – Scheff's Cat May 09 '20 at 07:49