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

后端 未结 12 1803
余生分开走
余生分开走 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:15

    You wouldn't get a division by zero regardless of the value of a - b, since floating point division by 0 doesn't throw an exception. It returns infinity.

    Now, the only way a == b would return true is if a and b contain the exact same bits. If they differ by just the least significant bit, the difference between them will not be 0.

    EDIT :

    As Bathsheba correctly commented, there are some exceptions:

    1. "Not a number compares" false with itself but will have identical bit patterns.

    2. -0.0 is defined to compare true with +0.0, and their bit patterns are different.

    So if both a and b are Double.NaN, you will reach the else clause, but since NaN - NaN also returns NaN, you will not be dividing by zero.

提交回复
热议问题