C#双加成 - 奇怪的行为 [英] C# double addition - strange behaviour

查看:142
本文介绍了C#双加成 - 奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static void Main()
{
    Dictionary<string, double> values = new Dictionary<string, double>();
    values.Add("a", 0.002);
    values.Add("b", 0.003);
    values.Add("c", 0.012);

    // Summing iteratively.
    double v1 = 615.0;
    foreach (KeyValuePair<string, double> kp in values)
    {
        v1 += kp.Value;
    }

    Console.WriteLine(v1);

    // Summing using the Sum method.
    double v2 = 615.0;
    v2 += values.Values.Sum();

    Console.WriteLine(v2);

    Console.ReadLine();
}

当我看到在调试器V1的值它给出的值615.01699999999994但对于V2它给人的615.017值。出于某种原因,数总和法得出一个准确的结果,而对它们求和迭代没有。 (当我打印两个值它们是相同的,但我想这是由于一些四舍五入的WriteLine方法一样。)

When I look at the value of v1 in the debugger it gives a value of 615.01699999999994 but for v2 it gives a value of 615.017. For some reason the Sum method yields an accurate result whereas summing them iteratively does not. (When I print the two values they are the same, but I presume this is due to some rounding that the WriteLine method does.)

任何人都知道是怎么回事?

Anyone know what is going on here?

推荐答案

浮点运算本身是不是100%准确,有误差。在其中添加不同的数字加在一起的顺序会影响多少浮点错误存在。如果是重要的这些计算是完全准确的,你应该使用十进制,而不是增加一倍。

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.

这不会有什么用点心与手动总结数据。在第一个你,你去每个号码增加至615,在第二个添加了所有的数字给对方一个的然后的将它们添加到615这是添加相同数据的不同排序。根据你使用任何一种方法哪些号码可能会导致更多或更少的错误。

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.

这篇关于C#双加成 - 奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆