問題描述
class Test{
public static void main(String[] args){
float f1=3.2f;
float f2=6.5f;
if(f1==3.2){
System.out.println("same");
}else{
System.out.println("different");
}
if(f2==6.5){
System.out.println("same");
}else{
System.out.println("different");
}
}
}
輸出:
different
same
為什么是這樣的輸出?我希望 same
與第一種情況的結果相同.
Why is the output like that? I expected same
as the result in first case.
推薦答案
不同的是,6.5 可以用 float 和 double 精確表示,而 3.2 不能用任何一種類型精確表示.并且兩個最接近的近似值是不同的.
The difference is that 6.5 can be represented exactly in both float and double, whereas 3.2 can't be represented exactly in either type. and the two closest approximations are different.
float 和 double 之間的相等比較首先將 float 轉換為 double,然后比較兩者.所以數據丟失.
An equality comparison between float and double first converts the float to a double and then compares the two. So the data loss.
您永遠不應該比較浮點數或雙精度數是否相等;因為您不能真正保證分配給 float 或 double 的數字是準確的.
You shouldn't ever compare floats or doubles for equality; because you can't really guarantee that the number you assign to the float or double is exact.
這種舍入誤差是浮點計算的一個特征.
將無限多個實數壓縮為有限位數需要一個近似的表示.雖然有無限許多整數,在大多數程序中整數計算的結果可以以 32 位存儲.
Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits.
相反,給定任意固定位數,大多數實數計算將產生的數量不能用那么多位精確表示.因此浮點計算的結果通常必須按順序四舍五入以適應其有限的表示.這個舍入誤差是浮點計算的特征.
In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.
查看每個計算機科學家都應該了解的浮點運算知識更多!
這篇關于為什么在 Java 中比較浮點數不一致?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!