问题描述
我想比较 PHP 中的两个浮点数,就像在这个示例代码中一样:
I want to compare two floats in PHP, like in this sample code:
$a = 0.17;
$b = 1 - 0.83; //0.17
if($a == $b ){
echo 'a and b are same';
}
else {
echo 'a and b are not same';
}
在这段代码中,它返回 else
条件而不是 if
条件的结果,即使 $a
和 $b
是一样的.有没有什么特殊的方法来处理/比较 PHP 中的浮点数?
In this code it returns the result of the else
condition instead of the if
condition, even though $a
and $b
are same. Is there any special way to handle/compare floats in PHP?
如果是,请帮我解决这个问题.
If yes then please help me to solve this issue.
还是我的服务器配置有问题?
Or is there a problem with my server config?
推荐答案
如果你这样做,它们应该是一样的.但请注意,浮点值的一个特性是看起来会产生相同值的计算实际上不需要完全相同.因此,如果 $a
是文字 .17
并且 $b
通过计算到达那里,它们很可能是不同的,尽管两者都显示相同的值.
If you do it like this they should be the same. But note that a characteristic of floating-point values is that calculations which seem to result in the same value do not need to actually be identical. So if $a
is a literal .17
and $b
arrives there through a calculation it can well be that they are different, albeit both display the same value.
通常你永远不会像这样比较浮点值的相等性,你需要使用可接受的最小差异:
Usually you never compare floating-point values for equality like this, you need to use a smallest acceptable difference:
if (abs(($a-$b)/$b) < 0.00001) {
echo "same";
}
类似的东西.
这篇关于比较 php 中的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!