Monte Carlo simulation of the distribution of wealth

Foreword

With the start of school network class, in fact, this blog is to record my first job, but the conclusion is still a little meaning. I do not know why I recently updated every day, in fact, this year I was hesitant in the end this form of examination is not that something certainly I know some people will say this time is still hesitant already spent, and I have done a review entitled brush a few times ...... like, I just want to say ah, now you really are powerful, but there are too many uncertain future, do not simply dismiss a person, do not believe look at the following content.

text

First, let's look at this issue

Here Insert Picture Description
Simplify it, it is a total of approximately 100 people, the initial capital of 100 yuan per person, per day to give $ 1, will also receive money to other people, the same as the probability of each person get money.

Case 1: humane ideal state

In this state the initial conditions remain unchanged, but some people once wealth is zero, he would not go to someone else money, only to get someone to give money, if the government of subsistence allowances.

#初始化条件
person_id = [x for x in range(1,101)]
fortune = pd.DataFrame([100 for i in range(100)], index = person_id)
fortune.index.name = 'id'

def game1(data, roundi):
    if len(data[data[roundi - 1] == 0])>0:
        #当没有钱的时候不会支出
        round_i = pd.DataFrame({'pre_round':data[roundi-1],'lost':0})
        con = round_i['pre_round'] > 0
        round_i['lost'][con] = 1
        round_player_i = round_i[con]
        choice_i = pd.Series(np.random.choice(person_id, len(round_player_i)))
        gain_i = pd.DataFrame({'gain':choice_i.value_counts()})
        
        round_i = round_i.join(gain_i)
        round_i.fillna(0,inplace=True)
        return round_i['pre_round'] - round_i['lost'] + round_i['gain']
    else:
        # 对于不包含财富值为0 的状况
        round_i = pd.DataFrame({'pre_round':data[roundi-1],'lost':1})
        choice_i = pd.Series(np.random.choice(person_id, len(round_i)))
        gain_i = pd.DataFrame({'gain':choice_i.value_counts()})
        round_i = round_i.join(gain_i)
        round_i.fillna(0,inplace=True)
        return  round_i['pre_round'] - round_i['lost'] + round_i['gain']

#模拟10000次
for roundi in range(1, 10000):
    if roundi%1000==0:
        print('进行第%d次模拟' % roundi)
    fortune[roundi]  = game1(fortune, roundi)
    
game1_result = fortune.T
def draw(data, start, end, length):
    for n in list(range(start, end,length)):
        datai =data.iloc[n].sort_values().reset_index()[n]
        plt.figure(figsize=(10,6))
        sns.barplot(datai.index, datai.values)
        plt.xlim((0,100))
        plt.ylim((0,400))
        plt.title('模拟的轮数%s' % n)
        plt.xlabel('ID') 
        plt.ylabel('拥有的财富')
        plt.grid(alpha=0.5, linestyle='--')

draw(game1_result, 0,10000,1000)

Here Insert Picture Description
The last state of each person's wealth above. Like half the normal distribution, because there may be the same as the probability of right low left high after all, everyone get the money. In this case, some people will be very rich, and some people will be opposed only by guaranteeing

Case 2: A more realistic situation

Here Insert Picture Description
Here, I do not consider social assistance, and the people are divided into different types, contingent liabilities, there is hard work, investment, but also technological progress ...... different initial capital of each of them, the probability of obtaining income also Different.

# 初始化参数

#一共分配(游戏)2000次
N=2000


#投机者(负债但是仍然消费)20人
tj_id=[i for i in range(20)]
tj=pd.DataFrame([0 for i in range(20)],index=tj_id)

#努力工作者(可能现在财富并不多拥有60,但是获得利益的概率多1%)占大多数50人
nl_id=[i for i in range(20,70)]
nl=pd.DataFrame([60 for i in range(50)],index=nl_id)

#投资者(本身就很富有拥有100,而且很会投资,每次获得收益概率多3%)5人
tz_id=[i for i in range(70,75)]
tz=pd.DataFrame([100 for i in range(5)],index=tz_id)


#剩下就是知识进步(现在可能很不富有,拥有30,但是有知识有10%的概率获得利益)25人
zs_id=[i for i in range(75,100)]
zs=pd.DataFrame([30 for i in range(25)],index=zs_id)

# 将上面定义的人群合并起来
person=pd.concat([tj,nl,tz,zs])
person.head()

The distribution of wealth is the beginning of this
Here Insert Picture Description
and then we return based on the probability distribution given above, to calculate the probability of different people to get benefits.
For example, the probability of return of more than 1% of those efforts, their income is 0.01 * 0.01 + 1%; probability calculation of earnings like this probability behind three types of people, the last remaining points to debtors, began to see the results of the simulation

#定义游戏(分配规则)

#得到钱的机会(也就是收益概率不同)
chance=np.concatenate((np.array([0.008425]*20),np.array([0.0101]*50),np.array([0.0103]*5),np.array([0.011]*25)))
#0.01*0.01+0.01
#得到失去钱的id
def get_fromid(id_from):
    id_to=np.random.choice(a=np.arange(100),size=1,replace=False,p=chance)
    #不能自己给自己钱
    if id_to==id_from:
        id_to=get_fromid(id_from)
    return id_to

def game2(data,time):
    for i in range(time):
        if i%500==0:
            print(f"正在模拟第{i}轮")
        for id_from in range(0,len(data)):
            id_to=get_fromid(id_from)
            data['money'][id_from]-=1
            data['money'][id_to]+=1
    return data

final=game2(person,N)
plt.figure(figsize=(10,6))
sns.barplot(final.index,final.money)
plt.title("模拟2000轮后的结果")
plt.xlabel("人群ID")
plt.xticks(np.arange(0,101,10),np.arange(0,101,10)) 
plt.ylabel("所拥有财富")
plt.show()

Here Insert Picture Description
We found that debtors debt situation will be more serious, although efforts are also liabilities will arise, but still more than most of the previous wealth; investors are definitely getting rich, but look learners, people like us , beginning perhaps just a poor boy, but with the final wealth on its own strength, luck and other factors beyond the catch even investors;
of course, this is just a chicken soup, there is no use trying? The answer is certainly useful, but just by efforts to make your own strength gains than others 7% probability of it? Difficult, basically unrealistic, and often also our luck and the grasp of the relevant form. Wealthy people who are able to adapt to the times, in 2014, when just beginning to live, perhaps no one is interested, but three years later in 2017 the industry live fire, then there may just be a small anchor, holding a computer and a few spectators chat anchor, now perhaps a million people sought after big anchor. Take for instance my own experience, I was in the penguin gaming and Zhang Tai Sin basically not many viewers, of course, than I am sure he was a good point, and later because there is no audience, revenue is not ideal, school, etc. and other factors I gave up, although now it has been broadcast industry in decline, but he is still worth a lot of money, the platform contract price everyone should have a number. Like many, Gu Ying like a tentacle is the beginning of the study period live, but he persevered.
Let's look at a short video in recent years began to fire up, three or four minutes to make a video of an ordinary man became a net red, vlog can share life with one million up slowly become the main, this information age, change soon, however followed by more opportunities. I remember reading a book before, about a person's life have a chance to change the fate of three or four, caught can change your life, for now, the opportunity will be more often. Having said that, back to our question, look at the third case.

Case three: debtors will try

This model, I pulled out the 10 debtors to enable them to benefit from increased probability of 1%, which means that the first ten debtors will be even worse, a look

#得到钱的机会(也就是收益概率不同)
chance2=np.concatenate((np.array([0.00675]*10),np.array([0.0101]*10),np.array([0.0101]*50),np.array([0.0103]*5),np.array([0.011]*25)))

#得到失去钱的id
def get_fromid2(id_from):
    id_to=np.random.choice(a=np.arange(100),size=1,replace=False,p=chance2)
    #不能自己给自己钱
    if id_to==id_from:
        id_to=get_fromid2(id_from)
    return id_to

def game3(data,time):
    for i in range(time):
        if i%500==0:
            print(f"正在模拟第{i}轮")
        for id_from in range(0,len(data)):
            id_to=get_fromid2(id_from)
            data['money'][id_from]-=1
            data['money'][id_to]+=1
    return data

final2=game3(person,N)
plt.figure(figsize=(10,6))
sns.barplot(final2.index,final2.money)
plt.title("模拟2000轮后的结果")
plt.xlabel("人群ID")
plt.xticks(np.arange(0,101,10),np.arange(0,101,10)) 
plt.ylabel("所拥有财富")
plt.show()

Here Insert Picture Description
As it can be seen from the above comparison, when the debt is still harder, will reduce the level of debt; of course, if enough effort (to improve the probability of money), but also could become a positive asset.
And we can also see efforts by debtors effort is also possible to make the same efforts are also liabilities
Here Insert Picture Description
Here Insert Picture Description
contrast can be seen, even if the initial situation is different, but the same effort, the debtors as possible the efforts were dragged into the water, and more Moreover, debtors tend to be harder to change.

A process analysis of data to look at the job

  • First of all it, data analysis, the first step is to collect data (reptiles, public data, task data ......)
  • After getting the data to make it clear what we need to analyze, clear analysis of roughly direction
  • Data is then washed, data preprocessing, in order to ensure the validity of data to be reasonable and
  • For the most part we will be partitioned data sets, algorithms or mathematical models constructed according to the specific issues to analyze (using machine learning algorithms, deep learning networks, genetic algorithms ......), and finally get a neither underfitting also but fit, has good robustness of the model
  • Final result we will visualize, people can visually see the process and the results of the analysis, the corresponding conclusions
  • To summarize sometimes more clearly, need to write analysis reports, analysis ppt

Then we look at this job, it is their own definition of the data, so do not wash. There is no other modeling portion of the model used, mainly the Monte Carlo method, using probability and plenty of close to reality. This method before B station Additional up main analog propagation infect new crown virus from simple find pi value, almost all Probability can use it to get the results by experiment; Finally, of course in each model by a corresponding visualization FIG. They are given their own conclusions, As Well teacher reports and the like did not ask, so I do not do it. (Lazy Hee hee hee)

to sum up

In fact, this model has not completely realistic, for example, investors how to benefit may have been, there will be a loss of time; learners benefit probability is too high; of course, there are also government assistance ...... these problems will affect the final results of the simulation , but the general conclusion is the same, as long as you benefit large probability (strength, effort, luck, to grasp the trend of the times ......), you will be rich

Come to talk about beginning to say, do not easily deny a person. From the above example we can see that, even if the initial situation is different, but the same efforts are often the starting point of good people will be pulled into the water. And the value above is just my own definition, perhaps a good starting point because people will be too tired and too early to review the late lax, good starting point for people to work harder; I know that this time must be someone watching will say, said cut I do not just want to own a lot of comfort, but also to find so many excuses. In this regard, I can only say I admire those who are determined to study section, but not now also seriously review the impact of the epidemic. As for me, first of all in the end I thought a good case can not feel at ease at home to review, and I have too much to worry about things every day, my mother in the front line to save people, I am a person at home to find ways to fill his stomach (do not ask I did not my father, not as a living dead man), nothing to eat at home, this time in Hubei express can not send (a few days ago to buy things not send SF plus shipping), go out to buy is not easy; have a day Internet classes, homework. Perhaps you up in the morning, grooming can eat rice, but I have to start from cooking rice washing vegetables, and then go to class, eat the first meal of the day a little in the afternoon, at night they still washing dishes Xiguo, so I've been not determined graduate school. However, when I write these words, I decided to graduate school , not for anything else, I want my life more fulfilling, even if the last time effort just moved his good, all the experience will only make me life is more interesting is not it?

Published 85 original articles · won praise 55 · views 20000 +

Guess you like

Origin blog.csdn.net/shelgi/article/details/104402466