Unexpected results for floating point equals

前端 未结 2 1178
遇见更好的自我
遇见更好的自我 2021-01-29 07:51

Question is not about why 0.1 + 0.9 is not equals 1.0. Its about different behaviour of a equals.

Can someone explain why examples below works

2条回答
  •  自闭症患者
    2021-01-29 08:30

    The problem is due to the fact that the intermediate calculations are being performed in a higher precision, and the rules for when to round back to float precision are different in each case.

    According to the docs

    By default, in code for x86 architectures the compiler uses the coprocessor's 80-bit registers to hold the intermediate results of floating-point calculations.

    ... the compiler performs rounding on variables of type float to the correct precision for assignments and casts and when parameters are passed to a function"

    float summ = q + w is an assignment, and hence is rounded to the nearest float, which in this case is 1.

    q + w == 1.0f is neither a cast, assignment or function call, so the result of the addition is still an extended precision float, which is close, but not equal, to 1.

提交回复
热议问题