public static double[] percent(int reservedBits, double theRatioOfTheCombination, double[] data) {
int[] order = new int[data.length];
for (int i = 0; i < data.length; ++i) {
order[i] = i;
}
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i];
}
double[] change = new double[data.length];
double[] diff = new double[data.length];
//构造精度规范
String format = "#.";
for (int i = 0; i < reservedBits; i++) {
format += '0';
}
DecimalFormat df = new DecimalFormat(format);
//把值换成这一部分的百分比并计算误差。再根据误差的大小进行排序
for (int i = 0; i < data.length; i++) {
change[i] = Double.parseDouble(df.format(data[i] / sum * theRatioOfTheCombination));
diff[i] = data[i] / sum * theRatioOfTheCombination - change[i];
}
sort(data, diff, order, change);
processError(change, theRatioOfTheCombination, df, data, reservedBits);
double[] result = new double[change.length];
for (int j = 0; j < change.length; j++) {
for (int k = 0; k < change.length; k++) {
if (j == order[k]) {
result[j] = change[k];
}
}
}
return result;
}
/**
* 对数组按误差大小进行排序
*/
private static void sort(double[] data, double[] diff, int[] order, double[] change) {
double temp1;
int temp2;
for (int i = 1; i < data.length; i++) {
for (int j = 0; j < data.length - i; j++) {
if (diff[j] > diff[j + 1]) {
temp1 = diff[j];
diff[j] = diff[j + 1];
diff[j + 1] = temp1;
temp1 = change[j];
change[j] = change[j + 1];
change[j + 1] = temp1;
temp2 = order[j];
order[j] = order[j + 1];
order[j + 1] = temp2;
}
}
}
}
/**
* 对数据的误差进行处理
*/
private static void processError(double[] change, double theRatioOfTheCombination, DecimalFormat df, double[] data, int reservedBits) {
double count = 0;
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i];
}
for (int i = 0; i < change.length; i++) {
count += change[i];
}
//对误差按其占比进行分配
double difference = theRatioOfTheCombination - count;
double ans = 0;
for (int i = 0; i < change.length; i++) {
change[i] = Double.parseDouble(df.format(change[i] + difference * data[i] / sum));
ans += change[i];
}
double left = Double.parseDouble(df.format(theRatioOfTheCombination - ans));
int i = change.length - 1;
double min = Double.parseDouble(df.format(Math.pow(10, -reservedBits)));
//对数据按与其四舍五入的数值相比的大小分别进行处理
while (Math.abs(left - 0) > 0.00001) {
if (left > 0) {
change[i] = Double.parseDouble(df.format(change[i] + min));
i--;
left = Double.parseDouble(df.format(left - min));
if (i == -1) {
i = change.length - 1;
}
} else {
change[i] = Double.parseDouble(df.format(change[i] - min));
i--;
left = Double.parseDouble(df.format(left + min));
if (i == -1) {
i = change.length - 1;
}
}
}
}
注:排序比较那要加上Math.abs