Should we compare floating point numbers for equality against a *relative* error?

前端 未结 5 1433
闹比i
闹比i 2020-11-30 09:13

So far I\'ve seen many posts dealing with equality of floating point numbers. The standard answer to a question like \"how should we decide if x and y are equal?\" is

<
5条回答
  •  醉酒成梦
    2020-11-30 09:33

    It all depends on the specific problem domain. Yes, using relative error will be more correct in the general case, but it can be significantly less efficient since it involves an extra floating-point division. If you know the approximate scale of the numbers in your problem, using an absolute error is acceptable.

    This page outlines a number of techniques for comparing floats. It also goes over a number of important issues, such as those with subnormals, infinities, and NaNs. It's a great read, I highly recommend reading it all the way through.

提交回复
热议问题