Home 基尼系数
Post
Cancel

基尼系数

基尼系数

基尼系数=差值综合/(2人数财富总和) 【注意:】因为基尼系数是0-1的小数所以使用double

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public static void main(String [] args){
        int n=100;
        int t = 1000000000;
        System.out.println("人数:"+n);
        System.out.println("轮数:"+t);
        experiment(n,t);

    }
    public static void experiment(int n,int t){
        double[] wealth = new double[n];
        Arrays.fill(wealth,100);
        boolean[] hasMoney = new boolean[n];
        for (int i = 0;i<t;i++){
            Arrays.fill(hasMoney,false);
            for(int j=0;j<n;j++){
                if(wealth[j]>0){
                    hasMoney[j]=true;
                }
            }
            for (int j=0;j<n;j++){
                if(hasMoney[j]){
                    int other = j;
                    do{
                        other = (int)(Math.random()*n);
                    }while(other ==j);
                    wealth[j]--;
                    wealth[other]++;
                }
            }
        }
        Arrays.sort(wealth);
        System.out.println("列出每个人的财富从贫穷到富有:");
        for(int i =0;i<n;i++){
            System.out.print((int)wealth[i]+ "");
            if(i%10 ==9){
                System.out.println();
            }
        }
        System.out.println();
        System.out.println("基尼系数为:"+calculateGini(wealth));
    }

    public static double calculateGini(double[] wealth){
        double sumOfAbsoluteDifferences = 0;
        double sumOfWealth = 0;
        int n = wealth.length;
        for (int i=0;i<n;i++){
            sumOfWealth += wealth[i];
            for(int j =0;j<n;j++){
                sumOfAbsoluteDifferences += Math.abs(wealth[i]-wealth[j]);
            }
        }
        return sumOfAbsoluteDifferences/(2*n*sumOfWealth);
    }
    
This post is licensed under CC BY 4.0 by the author.