find the variance of a list of numbers in csharp

To find the variance of a list of numbers in C#, you can use the following formula:

main.cs
variance = sum((x - mean)^2) / n
33 chars
2 lines

where x is each number in the list, mean is the average of the list, and n is the number of elements in the list.

Here's the C# code to calculate the variance of a list of numbers:

main.cs
using System;
using System.Collections.Generic;
using System.Linq;

public static class VarianceCalculator
{
    public static double CalculateVariance(List<double> numbers)
    {
        double mean = numbers.Average();

        double sum = 0;
        foreach (double x in numbers)
        {
            sum += Math.Pow(x - mean, 2);
        }

        double variance = sum / numbers.Count();
        return variance;
    }
}
429 chars
21 lines

You can then call this method with a list of numbers:

main.cs
List<double> numbers = new List<double> { 1, 2, 3, 4, 5 };
double variance = VarianceCalculator.CalculateVariance(numbers);
Console.WriteLine($"Variance: {variance}");
168 chars
4 lines

This will output:

main.cs
Variance: 2.5
14 chars
2 lines

gistlibby LogSnag