問題描述
我有以下代碼:
double x = 0;
{ ...do stuff ...}
if(x == 0){
}
我總是被教導(dǎo)不要檢查浮點(diǎn)數(shù)是否相等.檢查它是否等于零有什么不同嗎?
I was always taught that you shouldn't check floats for equality. Is checking to see if it is equal to zero any different?
推薦答案
你不應(yīng)該檢查浮點(diǎn)數(shù)是否相等的原因是浮點(diǎn)數(shù)不是完全精確的——存儲(chǔ)中有一些數(shù)字不準(zhǔn)確,比如那些這延伸到尾數(shù)和重復(fù)小數(shù)太遠(yuǎn)(請(qǐng)注意,我正在談?wù)撘?為底的重復(fù)小數(shù)).您可以將這種不精確性視為四舍五入".超出浮點(diǎn)數(shù)精度的數(shù)字將被截?cái)?,?shí)際上是向下舍入.
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.
如果它沒有改變,它將保持這種平等.但是,如果你稍微改變它,你可能不應(yīng)該使用等式,而是使用像 (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)
.
簡(jiǎn)而言之:只要你不是在很小的級(jí)別上玩 x 就可以了.
In short: as long as you're not playing with x at a very small level, it's OK.
這篇關(guān)于檢查雙重平等是否安全?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!