Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

PHP floating point comparison with greater than or less than operators

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";
}

What is the correct way of doing this with PHP?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  • Determine how much error there may be in the modeled values.
  • Determine whether you can tolerate slightly different exact amounts being reported equal due to floating-point errors, and what amount of difference you can tolerate (false positives).
  • Determine whether you can tolerate equal exact amounts being reported unequal due to floating-point errors (false negatives).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...