POW()似乎是由一个在这里被淘汰 [英] pow() seems to be out by one here

查看:191
本文介绍了POW()似乎是由一个在这里被淘汰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是怎么回事:

#include <stdio.h>
#include <math.h>
int main(void) {
    printf("17^12 = %lf\n", pow(17, 12));
    printf("17^13 = %lf\n", pow(17, 13));
    printf("17^14 = %lf\n", pow(17, 14));
}

我得到这样的输出:

I get this output:

17^12 = 582622237229761.000000
17^13 = 9904578032905936.000000
17^14 = 168377826559400928.000000

13和14不匹配钨ALPA CF:

12: 582622237229761.000000
    582622237229761

13: 9904578032905936.000000
    9904578032905937

14: 168377826559400928.000000
    168377826559400929

此外,这不是错了一些奇怪的分数 - 这正好跟一个错

Moreover, it's not wrong by some strange fraction - it's wrong by exactly one!

如果这倒给我什么深远的限制POW()能为我做的,就是在那里,可以计算出该选择?我需要一个可以计算 X ^是,其中 X ^是总是小于ULLONG_MAX的功能。

If this is down to me reaching the limits of what pow() can do for me, is there an alternative that can calculate this? I need a function that can calculate x^y, where x^y is always less than ULLONG_MAX.

推荐答案

POW 适用于双击号码。这些重形式S * 2 ^电子商务present号码其中s是一个53位整数。因此,双击可存储所有整数低于2 ^ 53,但只的部分的上述2 ^ 53的整数。特别是,它只能重新present偶数> 2 ^ 53,由于E> 0的值始终是2的倍数。

pow works with double numbers. These represent numbers of the form s * 2^e where s is a 53 bit integer. Therefore double can store all integers below 2^53, but only some integers above 2^53. In particular, it can only represent even numbers > 2^53, since for e > 0 the value is always a multiple of 2.

17 ^ 13需要54位来准确重新present,所以E设定为1,从而计算出的值变成偶数。正确的值是奇数,所以这并不奇怪它由一个人的了。同样,17 ^ 14需要58位重新present。这也推后一个是机缘巧合(只要你不施加太大的数论),这恰好是一次性从32的多个的,这是粒度在该双击如此规模的数字四舍五入。

17^13 needs 54 bits to represent exactly, so e is set to 1 and hence the calculated value becomes even number. The correct value is odd, so it's not surprising it's off by one. Likewise, 17^14 takes 58 bits to represent. That it too is off by one is a lucky coincidence (as long as you don't apply too much number theory), it just happens to be one off from a multiple of 32, which is the granularity at which double numbers of that magnitude are rounded.

有关详细的整数幂,你应该使用整数一路。自己写的双击 - 免费幂程序。通过平方,如果可以大量使用幂,但我相信它总是小于64,使这个问题没有实际意义。

For exact integer exponentiation, you should use integers all the way. Write your own double-free exponentiation routine. Use exponentiation by squaring if y can be large, but I assume it's always less than 64, making this issue moot.

这篇关于POW()似乎是由一个在这里被淘汰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆