douba6365 2013-12-02 07:26 采纳率: 100%
浏览 56
已采纳

PHP数学奇怪的行为

I have phantom bug in my code. It appears in one case from 10 attempts. When I try to debug it I found this strange behavior:

$a = floor(1385968017.8665 * 10000); // or (int) (1385968017.8665 * 10000)
// here $a equals to 13859680178664
$b = (1385968017.8665 * 10000);
// here $b equals to 13859680178665

I have such PHP version/configuration:

PHP 5.3.10-1ubuntu3.8 with Suhosin-Patch (cli) (built: Sep  4 2013 20:00:51) 
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies
with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

UPDATE: I know about floating operations precesion. Same code in C++:

#include <iostream>

int main()
{
    std::cout << std::fixed << (1385968017.8665 * 10000) << std::endl;
    std::cout << (unsigned long long) (1385968017.8665 * 10000) << std::endl;

    return 0;
}

gives me next output:

13859680178664.998047
13859680178664

And it was I expected from it. But why my PHP code shows that (1385968017.8665 * 10000) is precise equals to 13859680178665?

UPDATE 2: As user @core1024 mentioned in comments, PHP possible is rounding result of calculation (1385968017.8665 * 10000). If try php -r 'printf("%f ",1385968017.8665 * 10000);' result will be somewhere about 13859680178664.998047. Who can explain when and why PHP do this?

  • 写回答

3条回答 默认 最新

  • drwurqczo39355510 2013-12-03 09:33
    关注

    I found explanation for this problem. My php.ini precision setting is equal to 14. If I increase precision setting by one, this stragne behavior not represented:

    $a = floor(1385968017.8665 * 10000); // or (int) (1385968017.8665 * 10000)
    // here $a equals to 1385968017866(!)5
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊