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.

The second example may be more suitable as it rounds the result off to the nearest integer rather than truncates it.

Why not just use a loop. There can't be more than 31/63 integer multiplications without overflow anyway.

First one would be sufficient but you need to check the result double value before casting since it can be pretty larger than long's max.

Your first example is valid. It would be best to use a static_cast<>() instead of a c-style cast for clarity however. The second example you posted would give an incorrect result for small values and is superfluous.

It should be sufficient to do:

static_cast<long>(std::pow(static_cast<double>(a), b));

You should realise that this will overflow on large values of b.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top