Is it possible to get 0 by subtracting two unequal floating point numbers?

后端 未结 12 1819
余生分开走
余生分开走 2021-01-30 07:50

Is it possible to get division by 0 (or infinity) in the following example?

public double calculation(double a, double          


        
12条回答
  •  时光取名叫无心
    2021-01-30 08:17

    The supplied function can indeed return infinity:

    public class Test {
        public static double calculation(double a, double b)
        {
             if (a == b)
             {
                 return 0;
             }
             else
             {
                 return 2 / (a - b);
             }
        }    
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            double d1 = Double.MIN_VALUE;
            double d2 = 2.0 * Double.MIN_VALUE;
            System.out.println("Result: " + calculation(d1, d2)); 
        }
    }
    

    The output is Result: -Infinity.

    When the result of the division is to big to be stored in a double, infinity is returned even if the denominator is non-zero.

提交回复
热议问题