Strange multiplication result

前端 未结 1 2017
遥遥无期
遥遥无期 2021-01-27 08:57

In my code I have this multiplications in a C++ code with all variable types as double[]

f1[0] = (f1_rot[0] * xu[0]) + (f1_rot[1] * yu[0]); 
f1[1] = (f1_rot[0] *         


        
相关标签:
1条回答
  • 2021-01-27 09:52

    Your problem is an obvious result of what is called catastrophic summations: As we know, a double precision float can handle numbers of around 16 significant decimals.

    f1[1] = (f1_rot[0] * xu[1]) + (f1_rot[1] * yu[1])
          = -3.0299486605499998e-07 + 3.0299497080000003e-07
          = 1.0474500005332475e-13
    

    This is what we obtain with the numbers you have given in your example. Notice that (-7) - (-13) = 6, which corresponds to the number of decimals in the float you give in your example: (ex: -5.39155e-07 -3.66312e-07, each mantissa is of a precision of 6 decimals). It means that you used here single precision floats.

    I am sure that in your calculations, the precision of your numbers is bigger, that's why you find a more precise result.

    Anyway, if you use single precision floats, you can't expect a better precision. With a double precision, you can find a precision up to 16. You shouldn't trust a difference between two numbers, unless it is bigger than the mantissa:

    • Simple precision floats: (a - b) / b >= ~1e-7
    • Double precision floats: (a - b) / b >= ~4e-16

    For further information, see these examples ... or the table in this article ...

    0 讨论(0)
提交回复
热议问题