在解释语言上使用非常大的整数时出现意外结果 [英] Unexpected results when working with very big integers on interpreted languages
问题描述
我正在尝试获取1 + 2 + ... + 1000000000
的总和,但是我在PHP和
I am trying to get the sum of 1 + 2 + ... + 1000000000
, but I'm getting funny results in PHP and Node.js.
PHP
$sum = 0;
for($i = 0; $i <= 1000000000 ; $i++) {
$sum += $i;
}
printf("%s", number_format($sum, 0, "", "")); // 500000000067108992
Node.js
var sum = 0;
for (i = 0; i <= 1000000000; i++) {
sum += i ;
}
console.log(sum); // 500000000067109000
可以使用以下方法计算出正确答案
The correct answer can be calculated using
1 + 2 + ... + n = n(n+1)/2
正确答案= 500000000500000000 ,所以我决定尝试另一种语言.
Correct answer = 500000000500000000, so I decided to try another language.
GO
var sum , i int64
for i = 0 ; i <= 1000000000; i++ {
sum += i
}
fmt.Println(sum) // 500000000500000000
但是效果很好!那么我的PHP和Node.js代码有什么问题呢?
But it works fine! So what is wrong with my PHP and Node.js code?
也许这是解释语言的问题,这就是为什么它可以在像Go这样的编译语言下工作的原因?如果是这样,其他解释语言(例如Python和Perl)是否会遇到相同的问题?
Perhaps this a problem of interpreted languages, and that's why it works in a compiled language like Go? If so, would other interpreted languages such as Python and Perl have the same problem?
推荐答案
Python可以工作:
Python works:
>>> sum(x for x in xrange(1000000000 + 1))
500000000500000000
或者:
>>> sum(xrange(1000000000+1))
500000000500000000
Python的int
自动提升为支持任意精度的Python long
.它将在32或64位平台上产生正确的答案.
Python's int
auto promotes to a Python long
which supports arbitrary precision. It will produce the correct answer on 32 or 64 bit platforms.
这可以通过将2提高到远大于平台的位宽的幂来看到:
This can be seen by raising 2 to a power far greater than the bit width of the platform:
>>> 2**99
633825300114114700748351602688L
您可以(使用Python)证明您在PHP中获得的错误值是因为当值大于2 ** 32-1时,PHP会升为浮点数:
You can demonstrate (with Python) that the erroneous values you are getting in PHP is because PHP is promoting to a float when the values are greater than 2**32-1:
>>> int(sum(float(x) for x in xrange(1000000000+1)))
500000000067108992
这篇关于在解释语言上使用非常大的整数时出现意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!