在Java中操作和比较浮点数 [英] Manipulating and comparing floating points in java

查看:130
本文介绍了在Java中操作和比较浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,浮点运算没有精确表示。例如这个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)其中 / em>是一个很小的数字。



具有十进制形式的固定位数的浮点值不需要二进制形式的固定位数。



另外为了清楚起见:



虽然严格 == 比较浮点数的实际意义很小,严格的< / code>和> 比较,相反,是有效的用例(例子 - 当某个值超过阈值时逻辑触发:(val> threshold)&& panic();

In Java the floating point arithmetic is not represented precisely. For example this java code:

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

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 (Math.abs(a-b) < delta) where delta is a small number.

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 == 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();)

这篇关于在Java中操作和比较浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆