我读过你不应该直接比较 PHP 浮点数,因为可能会出现浮点精度错误。
我有一个浮点数,我需要根据浮点数所在的范围括号设置一个变量。像这样的东西-
$mytext;
if ($myfloat < 5.5) {
$mytext = "a";
} else if ($myfloat < 9.7) {
$mytext = "b";
} else {
$mytext = "c";
}
使用 PHP 执行此操作的正确方法是什么?
我读过你不应该直接比较 PHP 浮点数,因为可能会出现浮点精度错误。
我有一个浮点数,我需要根据浮点数所在的范围括号设置一个变量。像这样的东西-
$mytext;
if ($myfloat < 5.5) {
$mytext = "a";
} else if ($myfloat < 9.7) {
$mytext = "b";
} else {
$mytext = "c";
}
使用 PHP 执行此操作的正确方法是什么?
有些人建议不要将浮点数与相等运算符(例如==
or !=
)进行比较,但这种建议是错误的。相等运算符按应有的方式工作,没有错误。更好的建议更像是这样:浮点算术运算(包括类型之间的转换和从诸如“5.5”之类的数字转换)通常会引入舍入误差,因此浮点运算的计算结果通常与数学上的精确结果不同。如果您想确定用近似浮点建模的两个精确值是否相等,您应该:
At the very least, you should estimate the above. Then determine whether there is a test you can perform that returns results with acceptably low rates of false positives and of false negatives. Commonly, people use a test such as fabs(a-b) < ErrorThreshold
and guess at the ErrorThreshold.
Guessing is not engineering.
The above is for equality. Similar concerns apply to comparing for order (e.g., <
or <=
).
For the sample you show, the question would be how much you care about characterizing numbers that are very near the borders of 5.5 and 9.7. Is it okay if numbers slightly above or slightly below the border are put into the correct category? If so, use the tests as you have them. If it is not okay, you need to explain your criteria further, along with information about how much error in $myfloat
there may be.