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

更多相关文章

  1. 如何在PHP中自动设置用户的语言环境?
  2. 存储用户所需语言的最佳方式
  3. PHP 10个常见面试题及答案
  4. PHP语言的中回车换行
  5. (高分)我的win2000+php+Apache设置完后,默认语言不是中文...
  6. PHP的语言特性-面向对象和C++/java/python的相似之处
  7. 通过Bash脚本语言逃避MYSQL命令行。
  8. MySQL数据库笔记三:数据查询语言(DQL)与事务控制语言(TCL)
  9. Simple MySQL-C ORM - 简化C语言访问MySQL

随机推荐

  1. linux权限不够,sh不能用
  2. Linux下objdump查看C程序编译后的汇编代
  3. LINUX内核PCI扫描过程
  4. 解决僵尸进程
  5. 详解Linux内核之双向循环链表
  6. linux的sshd启动失败
  7. Linux服务器下日志截取
  8. Linux多线程——异步
  9. 来给你20个优秀的......前端轮播图插件
  10. android clipToPadding的一点理解