Strange output when comparing same float values?

后端 未结 3 1557
[愿得一人]
[愿得一人] 2020-12-18 15:33

Comparing Same Float Values In C

strange output in comparison of float with float literal

Float addition promoted to double?


I read the above l

3条回答
  •  臣服心动
    2020-12-18 15:52

    Floating point numbers are never accurate.

    This statement is wrong. Some floating point numbers are accurate, such as 1.0, 12345.0, 12345.5, -2.25. All these numbers can be represented as integers didived by a power of 2. All numbers that cannot also are not accurate.

    In your specific case, float x = 0.5 results in x having the value 1.00000000 * 2^-1. When you compare this against double 0.5, both operands are converted to double, so the comparison becomes 1.000000000000000 * 2^-1 == 1.000000000000000 * 2^-1, which succeeds.

    For float x = 0.1, it looks different. The value is stored as 1.01010101 * 2^-3 (or similar). Note that this is already not precise. When you compare this against double 0.1, the float is extended with zeros at the end, the comparison becomes 1.010101010000000 * 2^-3 == 1.010101010101010 * 2^-3, which fails.

提交回复
热议问题