Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

python - Distribution of outcomes in dice experiments

So I wrote a short Python function to plot distribution outcome of dice experiments. It's working fine but when I run for example dice(1,5000) or dice(10,5000) or dice(100,5000) the histograms shows a skewed distribution (high preference for 6). However, the average shows the to-be expected value of around 3.5. I thought maybe this has sth to do with the random number generation so I tried out 2 methods: 1st with random.randint and the 2nd one is as in code. However, they deliver similar results. Like there is something wrong with the upper limit. But I'm not sure why there is such a skewed distribution.

import matplotlib.pyplot as plt
import numpy as np
import random

# Throw a dice
def dice(N,n):
    result = np.zeros((n,N))
    '''
    N: number of dices
    n: number of experiment
    '''
    for i in range(n):
        for j in range(N):
            random_number = random.random()
            outcome = int(random_number * 6 + 1)
            result[i][j]=outcome
    laverage = np.mean(result)

    print('Result of throwing %d dice(s) for %d times:'%(N,n),result)
    print(laverage)
    plt.hist(np.resize(result,(N*n,1)),bins=[x for x in range(1,7)])
    plt.xlabel('Outcome')
    plt.ylabel('Number of occurences')
    plt.show()

dice(1,5000)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your plot is only showing 5 bars - the bar is to the right of the number, so I believe the results for 5 and 6 are being combined. If you change to range(1,8) you see more of what you expect.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...