在Java中操作和比较浮点数 [英] Manipulating and comparing floating points in java
问题描述
float a = 1.2;
float b = 3.0;
float c = a * b;
if(c == 3.6){
System.out.println(c is 3.6);
}
else {
System.out.println(c不是3.6);
}
打印c不是3.6。
我对3位以下的精度不感兴趣(#。###)。我怎样才能处理这个问题,以浮动乘法和比较可靠?
这是一个普遍规则,浮点数不应该(a == b)进行比较,而是像(Math.abs(ab)
具有十进制形式的固定位数的浮点值不需要二进制形式的固定位数。
另外为了清楚起见:
虽然严格 In Java the floating point arithmetic is not represented precisely. For example this java code: Prints "c is not 3.6". I'm not interested in precision beyond 3 decimals (#.###). How can I deal with this problem to multiply floats and compare them reliably? It's a general rule that floating point number should never be compared like (a==b), but rather like A floating point value having fixed number of digits in decimal form does not necessary have fixed number of digits in binary form. Addition for clarity: Though strict 这篇关于在Java中操作和比较浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! ==
比较浮点数的实际意义很小,严格的< / code>和
>
比较,相反,是有效的用例(例子 - 当某个值超过阈值时逻辑触发:(val> threshold)&& panic();
float a = 1.2;
float b= 3.0;
float c = a * b;
if(c == 3.6){
System.out.println("c is 3.6");
}
else {
System.out.println("c is not 3.6");
}
(Math.abs(a-b) < delta)
where delta is a small number.==
comparison of floating point numbers has very little practical sense, the strict <
and >
comparison, on the contrary, is a valid use case (example - logic triggering when certain value exceeds threshold: (val > threshold) && panic();
)