java豆知识——NFINITY,-INFINITY和NAN

1. 背景:

  • 在定位测试问题时意外的发现对float类型做除法,除数为0时,不会抛异常,只返回了结果NFINITY。然后将NFINITY放在list中再转成json,得到的返回值为null;此过程没有异常日志,定位颇周折,故在此处记录一下。
  • 注:此json的版本如下,其他版本的json没有出现返回值为null的情况:
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20131018</version>
        </dependency>
  • demo代码如下:
import org.json.JSONObject;
import java.util.ArrayList;
public class Test {
    public static void  main(String[] args) {
        ArrayList<Double> list = new ArrayList<>();
        list.add(23.2 / / 0);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("test", list);
        System.out.println(jsonObject.toString());
    }
}

2.java除法豆知识:

前提:当除数的值为0时:

  • 1.若除数和被除数都为整形,程序会报错,并抛出异常;
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Test.main(Test.java:14)
  • 2.若除数或被除数有任意一个为浮点型,则:
被除数返回
正数NFINITY,表示无限大
负数-NFINITY,表示无限小
0NAN,表示非数字

3.NFINITY与NAN的定义与使用

3.1.定义:
  • Double
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
public static final double NaN = 0.0d / 0.0;
  • Float
public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
public static final float NaN = 0.0f / 0.0;
3.2.应用:
  • 3.2.1.无限乘以0,结果为NAN:
System.out.println(Float.POSITIVE_INFINITY * 0); // output: NAN
System.out.println(Float.NEGATIVE_INFINITY * 0); // output: NAN
  • 3.2.2.无限除以0,结果不变,还是无限
System.out.println((Float.POSITIVE_INFINITY / 0) == Float.POSITIVE_INFINITY); // output: true
System.out.println((Float.NEGATIVE_INFINITY / 0) == Float.NEGATIVE_INFINITY); // output: true
  • 3.2.3.无限做除了乘以0意外的运算,结果还是无限
System.out.println(Float.POSITIVE_INFINITY == (Float.POSITIVE_INFINITY + 10000)); // output: true
System.out.println(Float.POSITIVE_INFINITY == (Float.POSITIVE_INFINITY - 10000)); // output: true
System.out.println(Float.POSITIVE_INFINITY == (Float.POSITIVE_INFINITY * 10000)); // output: true
System.out.println(Float.POSITIVE_INFINITY == (Float.POSITIVE_INFINITY / 10000)); // output: true
  • 3.2.4.判断一个浮点数是否为INFINITY,可用isInfinite方法
System.out.println(Double.isInfinite(Float.POSITIVE_INFINITY)); // output: true
  • 3.2.5.NAN表示非数字,它与任何值都不相等,甚至不等于它自己,所以要判断一个数是否为NAN要用isNAN方法:
System.out.println(Float.NaN == Float.NaN); // output: false
System.out.println(Double.isNaN(Float.NaN)); // output: true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值