JiangHongTiao
JiangHongTiao

Reputation: 885

Why List<float>.Sum() and manual sum of numbers gives different result in C#?

in C# I have following code:

public static float sum(List<float> array)
    {
        float result = 0.0f;
        for (int i = 0; i < array.Length; i++)
            result += array[i];

        float lSum = array.Sum();

        return result;
    }

Why result of those two 'different' approaches differs?

For an array of length 911380 elements result=620246 and lSum=620235.8

What is internal implementation of List.Sum and which answer is correct? Is it problem of C# language/library or does it depends on implementation of + in Windows?

We do research about human brain and heart activity and we need correct results, so I appreciate any kind of help! Thanks a lot in advance.

Upvotes: 3

Views: 2811

Answers (1)

Jakub Lortz
Jakub Lortz

Reputation: 14894

The Sum extension method uses a double to accumulate the result and only casts to float to return it, so it's more precise than using float:

public static float Sum(this IEnumerable<float> source) 
{
    if (source == null) throw Error.ArgumentNull("source");
    double sum = 0;
    foreach (float v in source) sum += v;
    return (float)sum;
}

Upvotes: 5

Related Questions