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

查看:25
本文介绍了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.出于某种原因,Sum 方法会产生准确的结果,而对它们进行迭代求和则不会.(当我打印这两个值时,它们是相同的,但我认为这是由于 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.

这与使用 Sum 与手动汇总数据没有任何关系.在第一个中,您将每个数字添加到 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天全站免登陆