# Theil’s Inequality Algorithm using C#

``` public class TheilInEqualityAlgorithm { private readonly int _holdOutPeriod; private readonly IEnumerable _actualAndPredictedValues; public TheilInEqualityAlgorithm(int holdOutPeriod, IEnumerable actualAndPredictedValues) { _holdOutPeriod = holdOutPeriod; _actualAndPredictedValues = actualAndPredictedValues; } private double CalculateRootMeanSquareDeviation() { double sum = 0; foreach (ActualAndPredictedValue actualAndPredictedValue in _actualAndPredictedValues) { double difference = actualAndPredictedValue.Actual - actualAndPredictedValue.Predicted; double squareOfdifference = Math.Pow(difference, 2); sum = sum + squareOfdifference; }```

``` ```

```double rootMeanSquareDeviation = Math.Sqrt(sum / _holdOutPeriod); return rootMeanSquareDeviation; } public Dictionary<string,double> CalculateTheilInEquality() { var results=new Dictionary<string, double>(); double calculatedRootMeanSquareDeviation = CalculateRootMeanSquareDeviation(); results.Add("RMSD",calculatedRootMeanSquareDeviation); double actualSquareSum = 0; double predictedSquareSum = 0; foreach (ActualAndPredictedValue actualAndPredictedValue in _actualAndPredictedValues) { double actualSquare = Math.Pow(actualAndPredictedValue.Actual, 2); double predictedSquare = Math.Pow(actualAndPredictedValue.Predicted, 2); actualSquareSum = actualSquareSum + actualSquare; predictedSquareSum = predictedSquareSum + predictedSquare; } double sqrtOfActualSum = Math.Sqrt(actualSquareSum / _holdOutPeriod); double sqrtOfPredictedSum = Math.Sqrt(predictedSquareSum / _holdOutPeriod); double theilInEquality = (calculatedRootMeanSquareDeviation) / (sqrtOfActualSum + sqrtOfPredictedSum); results.Add("TheilInEquality", theilInEquality); return results; } } public class ActualAndPredictedValue { public double Actual { get; set; } public double Predicted { get; set; } } ```
Pass actual and predicted values for the periods
``` var actualPredictedCollection = new List { new ActualAndPredictedValue { Actual =-659505.150000, Predicted =-900587.246911 }}; var results = new TheilInEqualityAlgorithm(12,actualPredictedCollection).CalculateTheilInEquality(); ```double theilInEquality=results[“TheilInEquality”];
Enjoy coding…