简体   繁体   English

如何在 C++ 中提高 int 或 long 的幂

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

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琐碎的问题:我只是想知道,如果一个人想将一个 int 或 long 提升到另一个 int 或 long 的幂,是否

(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.如果long是 32 位, double有效位是 53 位,通常情况下,不会有问题。

The second consideration is the accuracy of the pow function itself.第二个考虑是pow function本身的精度。 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.如果有任何可能低于实际值,则将结果加 0.5 是确保正确结果的唯一方法。

The expected result of your pow will always be an integer, so there's no harm in adding 0.5.pow的预期结果将始终是 integer,因此添加 0.5 没有任何害处。 I'd recommend that version.我会推荐那个版本。

You should write your own function.您应该编写自己的 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.第二个示例可能更合适,因为它将结果四舍五入到最接近的 integer 而不是截断它。

Why not just use a loop.为什么不只使用循环。 There can't be more than 31/63 integer multiplications without overflow anyway.无论如何,不能有超过 31/63 integer 乘法而不溢出。

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.第一个就足够了,但您需要在转换之前检查结果双精度值,因为它可能比 long 的最大值大得多。

Your first example is valid.你的第一个例子是有效的。 It would be best to use a static_cast<>() instead of a c-style cast for clarity however.但是,为了清楚起见,最好使用static_cast<>()而不是 c 样式的强制转换。 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.您应该意识到这将在 b 的较大值上溢出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM