Accord.Statistics.Measures.HistogramEntropy C# (CSharp) Method

HistogramEntropy() public static method

Calculate entropy value of an histogram.

The input array is treated as histogram, i.e. its indexes are treated as values of stochastic function, but array values are treated as "probabilities" (total amount of hits).

public static HistogramEntropy ( this values ) : double
values this Histogram array.
return double
        public static double HistogramEntropy(this int[] values)
        {
            int total = 0;
            double entropy = 0;
            double p;

            // calculate total amount of hits
            for (int i = 0; i < values.Length; i++)
                total += values[i];

            if (total != 0)
            {
                // for all values
                for (int i = 0; i < values.Length; i++)
                {
                    // get item's probability
                    p = (double)values[i] / total;
                    // calculate entropy
                    if (p != 0)
                        entropy += (-p * Math.Log(p, 2));
                }
            }

            return entropy;
        }