How to check dependencies of floats

前端 未结 5 1250
闹比i
闹比i 2020-12-10 13:25

I want to determine (in c++) if one float number is the multiplicative inverse of another float number. The problem is that i have to use a third variable to do it. For inst

5条回答
  •  清歌不尽
    2020-12-10 13:51

    The problem is that 0.2 cannot be represented exactly in binary, because its binary expansion has an infinite number of digits:

     1/5: 0.0011001100110011001100110011001100110011...
    

    This is similar to how 1/3 cannot be represented exactly in decimal. Since x is stored in a float which has a finite number of bits, these digits will get cut off at some point, for example:

       x: 0.0011001100110011001100110011001
    

    The problem arises because CPUs often use a higher precision internally, so when you've just calculated 1/y, the result will have more digits, and when you load x to compare them, x will get extended to match the internal precision of the CPU.

     1/y: 0.0011001100110011001100110011001100110011001100110011
       x: 0.0011001100110011001100110011001000000000000000000000
    

    So when you do a direct bit-by-bit comparison, they are different.

    In your second example, however, storing the result into a variable means it gets truncated before doing the comparison, so comparing them at this precision, they're equal:

       x: 0.0011001100110011001100110011001
       z: 0.0011001100110011001100110011001
    

    Many compilers have switches you can enable to force intermediate values to be truncated at every step for consistency, however the usual advice is to avoid doing direct comparisons between floating-point values and instead check if they differ by less than some epsilon value, which is what Gangnus is suggesting.

提交回复
热议问题