zoukankan      html  css  js  c++  java
  • 浮点数的除零(学习笔记)

    所有的浮点数值计算都遵循IEEE 754规范,用于表示溢出和出错情况的三个特殊的浮点数值,±inf、NaN。

    源码注释:

    If the argument is {@code 0x7ff0000000000000L}, the result is positive infinity.
    If the argument is {@code 0xfff0000000000000L}, the result is negative infinity.
    If the argument is any value in the range
    * {@code 0x7ff0000000000001L} through
    * {@code 0x7fffffffffffffffL} or in the range
    * {@code 0xfff0000000000001L} through
    * {@code 0xffffffffffffffffL}, the result is a NaN.

    Demo:1.0、0.0和0的浮点数值输出:

    double d1 = Double.parseDouble("1.0");
    BigDecimal bd1 = new BigDecimal(d1);
    System.out.println(bd1);//1
    
    double d2 = Double.parseDouble("0.0");
    BigDecimal bd2 = new BigDecimal(d2);
    System.out.println(bd2);//0
    
    double d3 = Double.parseDouble("0");
    BigDecimal bd3 = new BigDecimal(d3);
    System.out.println(bd3);//0

    从结果可以看出,1.0、0.0、0都不能使用二进制来准确的表示,所以只能使用最接近的浮点值来代替。

    1)1.0/0的结果是什么?为什么?

    Infinity

    原因:类型不同,低精度向高精度转化,相当于1.0/0.0(public static final double POSITIVE_INFINITY = 1.0 / 0.0;和Double.LongBitsToRawLongDouble(0x7ff0000000000000L))。

    通过doubleToRawLongBits方法来证明:

    double a = 1.0 / 0;
    long b = Double.doubleToRawLongBits(a);
    System.out.println(b);//9218868437227405312
    Long c=0x7ff0000000000000L;
    System.out.println(c.longValue());//9218868437227405312

    另一种解释:无限接近于1的数除以无限接近于0的数,举例:1/0.1=10;1/0.01=100;1/0.001=1000;1/0.0001=10000......无穷大。

    2)0/0的结果是什么?为什么?

    ArithmeticException

    原因:类型相同,无需转化。

    文档说明,Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.

  • 相关阅读:
    LeetCode Single Number
    Leetcode Populating Next Right Pointers in Each Node
    LeetCode Permutations
    Leetcode Sum Root to Leaf Numbers
    LeetCode Candy
    LeetCode Sort List
    LeetCode Remove Duplicates from Sorted List II
    LeetCode Remove Duplicates from Sorted List
    spring MVC HandlerInterceptorAdapter
    yum
  • 原文地址:https://www.cnblogs.com/1693977889zz/p/11632260.html
Copyright © 2011-2022 走看看