最近工作中做数据统计分析,按照正常的计算方式会出现比例之和大于或者小于100%,这里提供的C#的计算方法是来自echarts饼状图的最大余额法用来解决此问题。
private static double getPercentValue(long[] arr, int idx, int precision)
{
if ((arr.Length - 1) < idx)
{
return 0;
}
double sum = 0;
foreach (var j in arr)
{
sum += j;
}
if (sum == 0)
{
return 0;
}
double digits = Math.Pow(10, precision);
double[] votesPerQuota = new double[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
double val = arr[i] / sum * digits * 100;
votesPerQuota[i] = val;
}
double targetSeats = digits * 100;
double[] seats = new double[arr.Length];
for (int i = 0; i < votesPerQuota.Length; i++)
{
seats[i] = Math.Floor(votesPerQuota[i]);
}
double currentSum = 0;
foreach (var seat in seats)
{
currentSum += seat;
}
double[] remainder = new double[arr.Length];
for (int i = 0; i < seats.Length; i++)
{
remainder[i] = votesPerQuota[i] - seats[i];
}
while (currentSum < targetSeats)
{
double max = 0;
int maxId = 0;
for (int i = 0; i < remainder.Length; ++i)
{
if (remainder[i] > max)
{
max = remainder[i];
maxId = i;
}
}
++seats[maxId];
remainder[maxId] = 0;
++currentSum;
}
return seats[idx] / digits;
}
private static double[] getPercentValue(long[] arr, int precision)
{
double[] result = new double[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
result[i] = getPercentValue(arr, i, precision);
}
return result;
}
#endregion