自然均值算法

在某些数据显示时,由于数据并不是均匀分布的,导致显示太难看;

所以不能使用简单分组=(最大值-最小值)/组;

后来发现这个算法!

 

 

自然均值算法:

        /// <summary>
        ///  自然均值算法 !=(最大值-最小值)/分组数
        /// </summary>
        /// <param name="list">排序后的数组</param>
        /// <param name="numclass">分成几组</param>
        /// <returns>返回一个数组,长度=分组数-1</returns>
        /// 用法:若返回[1,2] 则 (<1, 1<=x<2, x>=2)
        public double[] GetJenksBreaks(double[] list, int numclass)
            {
                int numdata = list.Length;
                double[,] mat1 = new double[numdata + 1, numclass + 1];
                double[,] mat2 = new double[numdata + 1, numclass + 1];
                double[] st = new double[numdata];
                for (int i = 1; i <= numclass; i++)
                {
                    mat1[1, i] = 1;
                    mat2[1, i] = 0;
                    for (int j = 2; j <= numdata; j++)
                    {
                        mat2[j, i] = Double.MaxValue;
                    }
                }
                double v = 0.0;
                for (int l = 2; l <= numdata; l++)
                {
                    double s1 = 0.0;
                    double s2 = 0.0;
                    double w = 0.0;
                    for (int m = 1; m <= l; m++)
                    {
                        int i3 = l - m + 1;
                        double val = list[i3 - 1];
                        s2 += val * val;
                        s1 += val;
                        w++;
                        v = s2 - (s1 * s1) / w;
                        int i4 = i3 - 1;
                        if (i4 != 0)
                        {
                            for (int j = 2; j <= numclass; j++)
                            {
                                if (mat2[l, j] >= (v + mat2[i4, j - 1]))
                                {
                                    mat1[l, j] = i3;
                                    mat2[l, j] = v + mat2[i4, j - 1];
                                }
                            }
                        }
                    }
                    mat1[l, 1] = 1;
                    mat2[l, 1] = v;
                }
                int k = numdata;
                int[] kclass = new int[numclass];
                kclass[numclass - 1] = list.Length - 1;
                double[] kvalues = new double[numclass - 1];
                for (int j = numclass; j >= 2; j--)
                {
                    int id = (int)(mat1[k, j]) - 2;
                    kvalues[j - 2] = (double)list[id];
                    kclass[j - 2] = id;
                    k = (int)mat1[k, j] - 1;
                }
                return kvalues;
            }
View Code

 

posted @ 2019-07-11 10:05  hao_1234_1234  阅读(483)  评论(0编辑  收藏  举报