在解释语言上使用非常大的整数时,会产生意想不到的结果。
I am trying to get the sum of 1 + 2 + ... + 1000000000
, but I'm getting funny results in PHP and Node.js.
我想求1 + 2 +的和。+ 1000000000,但是我在PHP和Node.js中得到了有趣的结果。
PHP
PHP
$sum = 0;
for($i = 0; $i <= 1000000000 ; $i++) {
$sum += $i;
}
printf("%s", number_format($sum, 0, "", "")); // 500000000067108992
Node.js
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
Correct answer = 500000000500000000, so I decided to try another language.
正确答案= 500000000000000,所以我决定尝试另一种语言。
GO
去
var sum , i int64
for i = 0 ; i <= 1000000000; i++ {
sum += i
}
fmt.Println(sum) // 500000000500000000
But it works fine! So what is wrong with my PHP and Node.js code?
但它工作正常!PHP和节点有什么问题。js代码?
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?
也许这是解释语言的一个问题,这就是为什么它在像Go这样的编译语言中工作?如果是这样,其他解释语言(如Python和Perl)是否也会遇到同样的问题?
36 个解决方案
#1
156
Python works:
Python的作品:
>>> sum(x for x in xrange(1000000000 + 1))
500000000500000000
Or:
或者:
>>> sum(xrange(1000000000+1))
500000000500000000
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.
Python的int auto升级为Python long,支持任意精度。它将在32或64位平台上生成正确的答案。
This can be seen by raising 2 to a power far greater than the bit width of the platform:
这可以通过将2提升到远高于平台位宽的功率来体现:
>>> 2**99
633825300114114700748351602688L
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:
您可以(通过Python)演示在PHP中遇到的错误值,因为当值大于2* 32-1时,PHP将提升为浮点数:
>>> int(sum(float(x) for x in xrange(1000000000+1)))
500000000067108992
更多相关文章
- 如何在PHP中自动设置用户的语言环境?
- 存储用户所需语言的最佳方式
- PHP 10个常见面试题及答案
- PHP语言的中回车换行
- (高分)我的win2000+php+Apache设置完后,默认语言不是中文...
- PHP的语言特性-面向对象和C++/java/python的相似之处
- 通过Bash脚本语言逃避MYSQL命令行。
- MySQL数据库笔记三:数据查询语言(DQL)与事务控制语言(TCL)
- Simple MySQL-C ORM - 简化C语言访问MySQL