問題描述
我有以下代碼:
double x = 0;
{ ...do stuff ...}
if(x == 0){
}
我總是被教導不要檢查浮點數是否相等.檢查它是否等于零有什么不同嗎?
I was always taught that you shouldn't check floats for equality. Is checking to see if it is equal to zero any different?
推薦答案
你不應該檢查浮點數是否相等的原因是浮點數不是完全精確的——存儲中有一些數字不準確,比如那些這延伸到尾數和重復小數太遠(請注意,我正在談論以2為底的重復小數).您可以將這種不精確性視為四舍五入".超出浮點數精度的數字將被截斷,實際上是向下舍入.
The reason you shouldn't check floats for equality is that floating point numbers are not perfectly precise -- there's some inaccuracy in storage with some numbers, such as those that extended too far into the mantissa and repeating decimals (note that I'm talking about repeating decimals in base 2). You can think of this imprecision as "rounding down". The digits that extend beyond the precision of the floating-point number are truncated, effectively rounding down.
如果它沒有改變,它將保持這種平等.但是,如果你稍微改變它,你可能不應該使用等式,而是使用像 (x < 0.0001 && x > -.0001)
這樣的范圍.
If it has not changed, it will keep that equality. However, if you change it even slightly, you probably should not use equalities, but instead a range like (x < 0.0001 && x > -.0001)
.
簡而言之:只要你不是在很小的級別上玩 x 就可以了.
In short: as long as you're not playing with x at a very small level, it's OK.
這篇關于檢查雙重平等是否安全?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!