Comparing floating point values

前端 未结 3 1864
别跟我提以往
别跟我提以往 2020-11-27 21:12

I just read a statement about the floating point value comparison

Floating point values shall not be compared using either the == or != operators.

3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 21:40

    "Best method" depends on the circumstances of why you want to compare the numbers. In general, if you think you want to check if 2 floating points numbers are equal, you are doing something wrong.

    Floating point numbers are supposed to be used to represent real values, in both senses of the word. Is this object the same length as this other object? Well, they may look the same length, but if you get a good enough measuring device, you can always find a difference. Similarly, two floating point numbers are never equal, unless they are measuring the same thing, and have been processed in exactly the same way. Other than that, it's just a rounding error somewhere in the system.

    You might want to check that they are close, (closer than a certain threshold) as the other answers have suggested, but not equal.

提交回复
热议问题