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))
?
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.
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.
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