Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise an int or long to a power in C++

Tags:

c++

pow

Trivial question: I am just wondering, if one wants to raise an int or a long to the power of another int or long, does

(long)std::pow((double)a,(double)b)

suffice, or do I need

(long)(0.5 + std::pow((double)a,(double)b))

?

like image 492
Cookie Avatar asked Dec 09 '22 06:12

Cookie


2 Answers

There are two considerations. The first is roundoff due to inexactness of floating point representations; this won't be a problem in this case, because integers are perfectly representable as long as the number of bits is less than the bits of significand in the floating point. If long is 32 bits and double significand is 53 bits, as it usually is, there won't be a problem.

The second consideration is the accuracy of the pow function itself. If there's any possibility that it will come out lower than the actual value, adding 0.5 to round the result is the only way to ensure the proper result.

The expected result of your pow will always be an integer, so there's no harm in adding 0.5. I'd recommend that version.

like image 142
Mark Ransom Avatar answered Jan 04 '23 07:01

Mark Ransom


You should write your own function. That way you can handle overflow yourself, and you don't have to worry about rounding errors.

But of the two I would use the second.

like image 42
john Avatar answered Jan 04 '23 09:01

john