PHP浮点数与大于或小于运算符的比较 [英] PHP floating point comparison with greater than or less than operators

查看:72
本文介绍了PHP浮点数与大于或小于运算符的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读到,由于浮点精度错误的可能性,您不应该直接比较PHP浮点数.

I have read that you shouldn't compare PHP floating point numbers directly due to the possibility of floating point precision errors.

我有一个浮点数,我需要根据浮点数所处的范围设置变量.像这样-

I have a floating point number and I need to set a variable depending on the what range bracket the floating point number falls into. Something like this -

$mytext;

if ($myfloat < 5.5) {
  $mytext = "a";
} else if ($myfloat < 9.7) {
  $mytext = "b";
} else {
  $mytext = "c";
}

用PHP做到这一点的正确方法是什么?

What is the correct way of doing this with PHP?

推荐答案

有人建议不要将浮点数与相等运算符(例如 == != ),但此建议被误导了.相等运算符可以按预期工作,没有错误.更好的建议是这样的:浮点算术运算(包括类型之间的转换和数字的转换,例如"5.5")通常会引入舍入误差,因此浮点运算的计算结果通常会与数学上的精确结果有所不同.如果要确定用近似浮点建模的两个精确值是否相等,则应该:

Some people advise not to compare floating-point numbers with equality operators (such as == or !=), but this advice is misguided. The equality operators work as they should, without error. Better advice is more like this: Floating-point arithmetic operations (including conversion between types and conversion from numerals such as "5.5") typically introduce rounding errors, so computed results of floating-point operations will typically differ from mathematically exact results. If you desire to determine whether two exact values modeled with approximate floating-point are equal or not, you should:

  • 确定建模值中可能有多少误差.
  • 确定您是否可以容忍由于浮点错误而导致的报告的准确数量稍有不同,以及可以容忍的差异量(误报).
  • 确定您是否可以容忍由于浮点错误(假阴性)而被报告为不相等的确切金额.

至少,您应该估计以上情况.然后确定是否存在可以执行的测试,该测试以较低的误报率和误报率返回结果.通常,人们使用诸如 fabs(a-b)<ErrorThreshold 并猜测ErrorThreshold.

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.

猜测不是工程.

以上内容是为了平等.类似的问题也适用于比较订单(例如< < = ).

The above is for equality. Similar concerns apply to comparing for order (e.g., < or <=).

对于您显示的示例,问题是您要关心如何表征非常靠近5.5和9.7边界的数字.将略高于或略低于边界的数字放入正确的类别中可以吗?如果是这样,请在进行测试时使用它们.如果还不行,则需要进一步解释您的条件,以及有关 $ myfloat 中可能有多少错误的信息.

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.

这篇关于PHP浮点数与大于或小于运算符的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆