How to correctly and standardly compare floats?

后端 未结 8 1380
夕颜
夕颜 2020-11-27 04:30

Every time I start a new project and when I need to compare some float or double variables I write the code like this one:

if (fabs(prev.min[i] - cur->min         


        
8条回答
  •  萌比男神i
    2020-11-27 04:44

    This post has a comprehensive explanation of how to compare floating point numbers: http://www.altdevblogaday.com/2012/02/22/comparing-floating-point-numbers-2012-edition/

    Excerpt:

    • If you are comparing against zero, then relative epsilons and ULPs based comparisons are usually meaningless. You’ll need to use an absolute epsilon, whose value might be some small multiple of FLT_EPSILON and the inputs to your calculation. Maybe.
    • If you are comparing against a non-zero number then relative epsilons or ULPs based comparisons are probably what you want. You’ll probably want some small multiple of FLT_EPSILON for your relative epsilon, or some small number of ULPs. An absolute epsilon could be used if you knew exactly what number you were comparing against.

提交回复
热议问题