How can I add floats together in different orders, and always get the same total?

前端 未结 3 710
被撕碎了的回忆
被撕碎了的回忆 2021-01-02 13:38

Let\'s say I have three 32-bit floating point values, a, b, and c, such that (a + b) + c != a + (b + c). Is there a summa

3条回答
  •  忘掉有多难
    2021-01-02 14:18

    I am not quite sure that (a + b) + c != a + (b + c) when doing arithmetic in a program.

    However the rule of thumb with using floating point arithmetic on present day hardware is to never directly test for equality.

    For whatever application you have you should choose an epsilon that is small enough and use

    (abs(a - b) < epsilon)
    

    as the equality test.

提交回复
热议问题