算法
public class 算法002_财富分布基尼系数 {
@Test
public void test() {
System.out.println("一个社会的基尼系数是一个在0~1之间的小数");
System.out.println("基尼系数为0代表所有人的财富完全一样");
System.out.println("基尼系数为1代表有1个人掌握了全社会的财富");
System.out.println("基尼系数越小,代表社会财富分布越均衡;越大则代表财富分布越不均衡");
System.out.println("在2022年,世界各国的平均基尼系数为0.44");
System.out.println("目前普遍认为,当基尼系数到达 0.5 时");
System.out.println("就意味着社会贫富差距非常大,分布非常不均匀");
System.out.println("社会可能会因此陷入危机,比如大量的犯罪或者经历社会动荡");
System.out.println("测试开始");
int persons = 100;
int lunZhuanCounts = 10000;
System.out.println(calculateMoney(persons, lunZhuanCounts));
}
public double calculateMoney(int persons, int lunZhuanCounts) {
int[] money = new int[persons];
Arrays.fill(money, 100);
boolean[] hasMoney = new boolean[persons];
for (int i = 0; i < lunZhuanCounts; i++) {
Arrays.fill(hasMoney, true);
for (int j = 0; j < money.length; j++) {
if (money[j] > 0) {
hasMoney[j] = true;
}
}
for (int j = 0; j < persons; j++) {
int other = j;
do {
other = (int) (Math.random() * persons);
} while (other == j);
if (hasMoney[j] == true) {
money[j]--;
money[other]++;
}
}
}
return calculateGiNi(money);
}
public double calculateGiNi(int[] money) {
double moneySum = 0;
double moneyJueDuiZhiCha = 0;
for (int i = 0; i < money.length; i++) {
moneySum += money[i];
for (int j = 0; j < money.length; j++) {
moneyJueDuiZhiCha += Math.abs(money[i] - money[j]);
}
}
return moneyJueDuiZhiCha / (2 * money.length * moneySum);
}
}
测试
测试开始
0.567438
Process finished with exit code 0