2

我正在尝试在 PHP 中进行浮点比较时建立我需要的增量。我想仔细看看我的变量,看看有什么不同。

我有 2 个计算变量,$a,$b。

$a = some_function();

$b = some_other_function();

如何查看 PHP 使用的确切数字?

我想将它们与这个公式进行比较,我需要在其中指定增量:

$delta = 0.00001;
if (abs($a-$b) < $delta) {
  echo "identical";
}

var_dump($a, $b) 返回 1.6215;1.6215。但我知道它们并不完全相等,因为

var_dump($a === $b);

评估为假;

为什么不var_dump()打印内部值?

4

2 回答 2

10

在 PHP 中,浮点数的打印值取决于 PHP 配置的“精度”。

你可以改变它:

ini_set('precision', YOUR_DESIRED_PRECISION_AS_INTEGER);

例如与:

ini_set('precision', 18);

您的号码可能会显示如下内容:

浮动 1.62149999999999994

浮动 1.6214999999999995

So now the difference between them is clearer.

So your delta may be: $delta = 0.00000000000001; It really depends of the precision you are looking for.

If you need to do exact mathematical calculations, do have a look at the BC Math Functions.


References / Sources

PHP - Floating point numbers

PHP - Floating point numbers - User Contributed Notes - deminy at deminy dot net

Codepad

于 2012-12-10T11:54:10.337 回答
0

If you don't want to edit your configuration file... you could use the round(val, precision) in your some_function() and some_other_function(). That way you can return the results to the precision you want. Check:
http://php.net/manual/en/function.round.php

于 2012-12-10T12:17:38.587 回答