Floating point equality

前端 未结 6 2036
渐次进展
渐次进展 2021-02-02 06:27

It is common knowledge that one has to be careful when comparing floating point values. Usually, instead of using ==, we use some epsilon or ULP based equality test

6条回答
  •  醉梦人生
    2021-02-02 06:40

    Assuming IEEE 754 semantics, there are definitely some cases where you can do this. Conventional floating point number computations are exact whenever they can be, which for example includes (but is not limited to) all basic operations where the operands and the results are integers.

    So if you know for a fact that you don't do anything that would result in something unrepresentable, you are fine. For example

    float a = 1.0f;
    float b = 1.0f;
    float c = 2.0f;
    assert(a + b == c); // you can safely expect this to succeed
    

    The situation only really gets bad if you have computations with results that aren't exactly representable (or that involve operations which aren't exact) and you change the order of operations.

    Note that the C++ standard itself doesn't guarantee IEEE 754 semantics, but that's what you can expect to be dealing with most of the time.

提交回复
热议问题