C# double addition - strange behaviour

后端 未结 2 1024
慢半拍i
慢半拍i 2020-12-20 02:57
public static void Main()
{
    Dictionary values = new Dictionary();
    values.Add(\"a\", 0.002);
    values.Add(\"b\",         


        
相关标签:
2条回答
  • 2020-12-20 03:15

    Floating point math is inherently not 100% accurate and has error. The order in which you add different numbers together can affect how much floating point error there is. If it's important for these calculations to be completely accurate you should use decimal, not double.

    This doesn't have anything to do with using Sum vs. manually summing the data. In the first you add each number to 615 as you go, in the second you add all of the numbers to each other an then add them to 615. It's a different ordering of adding the same data. Depending on which numbers you use either method could potentially result in more or less error.

    0 讨论(0)
  • 2020-12-20 03:25

    The problem with double/float's is that they are binary numbers, aka 1000110.10101001 internally, and therefore only represent an approximate representation of your values.

    Read Jon Skeet's explanation: Difference between decimal, float and double in .NET?

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