将Java代码转换为PHP -在PHP中对双精度数执行数学运算时丢失有效数字


Conversion of Java code to PHP - loss of significant digits in php while performing mathematical operations on double numbers

我正在尝试将一些用Java编写的逻辑转换为PHP,并且在PHP中看到不同的输出,同时对双精度数字执行数学运算。

见下面的代码和输出

    --------- java --------------
    double x =  0.1*(double)37.17;
    System.out.print(x); // prints 3.7170000000000005  
    --------- PHP --------------
    $x =  0.1*(double)37.17;
    echo $x; // prints 3.717

为什么会发生这种情况?当我在一些对数运算中使用这些值时,结果会产生显著的差异。

问题不在于算术本身。问题是默认情况下PHP输出的浮点数在小数点后有两位数字。

您可以使用ini_set;例如

ini_set('precision', 17);

或者,您可以使用format_number将数字转换为字符串,并直接控制小数后面的位数。或者使用printf

查看更多信息:

  • https://www.leaseweb.com/labs/2013/06/the-php-floating-point-precision-is-wrong-by-default/
  • http://php.net/manual/en/function.number-format.php
  • http://php.net/manual/en/function.printf.php

他们喜欢3.7170000000000005或37.17。

默认情况下,使用PHP所需的最小小数位数进行双精度打印。


如果你需要确切的答案,试试

了解浮点数的基本知识

像这样重写代码,你可以把18f修改成你想要的。

$x = 0.1*37.17;
echo $x; // prints 3.717  
printf("%4.18f", $x)