Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::pow with integer parameters, comparing to an integer type

According to http://en.cppreference.com/w/cpp/numeric/math/pow , when std::pow is used with integer parameters, the result is promoted to a double.

My question is then the following:

How safe is to compare an integer type with the result of a std::pow(int1, int2)? For example, can the if below evaluate to true?

std::size_t n = 1024;
if(n != std::pow(2, 10))
    cout << "Roundoff issues..." << endl;

That is, is it possible that the result on the rhs can be something like 1023.99...9 so when converted to size_t becomes 1023?

My guess is that the response in a big NO, but would like to know for sure. I am using these kind of comparisons when checking for dimensions of matrices etc, and I wouldn't like to use a std::round everywhere.

like image 521
vsoftco Avatar asked Feb 12 '23 13:02

vsoftco


2 Answers

It is funny you should ask, because someone else on StackOverflow had a question that was caused by the very fact that pow applied to small integers did not compute the obvious result on their platform (see also my writeup).

So yes, when applying pow to small integers, both arguments and ideal mathematical result are exactly representable. This does not force the implementation of exp to return the mathematical result, because no standard specifies that pow cannot be inaccurate by more than one ULP. And at least one very popular platform provides by default a pow function that does not compute pow(10, 2) as 100, but you are free to take you chances with pow(2, N) and perhaps it will happen to always return the integer you are entitled to expect.

like image 95
Pascal Cuoq Avatar answered Feb 15 '23 11:02

Pascal Cuoq


pow on integer arguments when the result is exactly-representable should give you the right answer all the time. Problem is, it doesn't. There are modern platforms (lots of Linux distributions, for instance, both old and recent), where it doesn't. It's not too hard to find a bunch of SO questions where people give pow really nice inputs and it returns a horribly wrong answer.

like image 41
tmyklebu Avatar answered Feb 15 '23 12:02

tmyklebu