gpt4 book ai didi

java - 长数组的精确和

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:27:26 27 4
gpt4 key购买 nike

为了获得 long[] 的精确总和,我使用了以下代码段。

public static BigInteger sum(long[] a) {
long low = 0;
long high = 0;
for (final long x : a) {
low += (x & 0xFFFF_FFFFL);
high += (x >> 32);
}
return BigInteger.valueOf(high).shiftLeft(32).add(BigInteger.valueOf(low));
}

它可以很好地处理分成两半的数字,最后合并部分和。令人惊讶的是,这种方法也有效:

public static BigInteger fastestSum(long[] a) {
long low = 0;
long high = 0;
for (final long x : a) {
low += x;
high += (x >> 32);
}
// We know that low has the lowest 64 bits of the exact sum.
// We also know that BigInteger.valueOf(high).shiftLeft(32) differs from the exact sum by less than 2**63.
// So the upper half of high is off by at most one.
high >>= 32;
if (low < 0) ++high; // Surprisingly, this is enough to fix it.
return BigInteger.valueOf(high).shiftLeft(64).add(BigInteger.valueOf(low));
}

相信fastestSum应该按原样工作。我相信它可以工作,但在最后一步必须做更多的事情。但是,它通过了我所有的测试(包括大型随机测试)。所以我要问:有人可以证明它有效或找到反例吗?

最佳答案

fastestSum(new long[]{+1, -1})  => -18446744073709551616

关于java - 长数组的精确和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30695987/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com