Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 660
Rakshak Avatar asked May 09 '20 07:05

Rakshak


People also ask

What is exp in C?

C exp() The exp() function computes e (2.71828) raised to the power of the given argument.

What does EXP mean in C++?

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.


1 Answers

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.

like image 130
MikeCAT Avatar answered Oct 07 '22 02:10

MikeCAT