What's wrong with using == to compare floats in Java?

后端 未结 21 1896
你的背包
你的背包 2020-11-22 01:00

According to this java.sun page == is the equality comparison operator for floating point numbers in Java.

However, when I type this code:



        
21条回答
  •  再見小時候
    2020-11-22 01:32

    As mentioned in other answers, doubles can have small deviations. And you could write your own method to compare them using an "acceptable" deviation. However ...

    There is an apache class for comparing doubles: org.apache.commons.math3.util.Precision

    It contains some interesting constants: SAFE_MIN and EPSILON, which are the maximum possible deviations of simple arithmetic operations.

    It also provides the necessary methods to compare, equal or round doubles. (using ulps or absolute deviation)

提交回复
热议问题