返回顶部
扩大
缩小

Heaton

Python基础(十二) 模拟掷骰子demo

模拟掷骰子1.0





https://docs.python.org/3/library/random.html

'''
模拟掷骰子1.0
'''
import random

def roll_dice():
    """
        模拟掷骰子
    """
    roll = random.randint(1, 6)
    return roll

def main():
    """
        主函数
    """
    total_times = 10000
    # 初始化列表 [0, 0, 0, 0, 0, 0]
    result_list = [0] * 6

    for i in range(total_times):
        roll = roll_dice()
        for j in range(1, 7):
            if roll == j:
                result_list[j - 1] += 1

    for i, result in enumerate(result_list):
        print('点数{}的次数:{},频率:{}'.format(i + 1, result, result / total_times))

if __name__ == '__main__':
    main()

测试结果:

点数1的次数:1696,频率:0.1696
点数2的次数:1627,频率:0.1627
点数3的次数:1714,频率:0.1714
点数4的次数:1681,频率:0.1681
点数5的次数:1614,频率:0.1614
点数6的次数:1668,频率:0.1668

模拟掷骰子2.0




'''
模拟掷骰子2.0
'''
import random

def roll_dice():
    """
        模拟掷骰子
    """
    roll = random.randint(1, 6)
    return roll

def main():
    """
        主函数
    """
    total_times = 10000

    # 初始化列表 [0, 0, 0, 0, 0, 0]
    result_list = [0] * 11

    # 初始化点数列表
    roll_list = list(range(2, 13))
    roll_dict = dict(zip(roll_list, result_list))

    for i in range(total_times):
        roll1 = roll_dice()
        roll2 = roll_dice()

        for j in range(2, 13):
            if (roll1 + roll2) == j:
                roll_dict[j] += 1

    for i, result in roll_dict.items():
        print('点数{}的次数:{},频率:{}'.format(i, result, result / total_times))

if __name__ == '__main__':
    main()

测试结果:

点数2的次数:276,频率:0.0276
点数3的次数:560,频率:0.056
点数4的次数:820,频率:0.082
点数5的次数:1112,频率:0.1112
点数6的次数:1454,频率:0.1454
点数7的次数:1614,频率:0.1614
点数8的次数:1407,频率:0.1407
点数9的次数:1074,频率:0.1074
点数10的次数:867,频率:0.0867
点数11的次数:527,频率:0.0527
点数12的次数:289,频率:0.0289

模拟掷骰子3.0





https://matplotlib.org/gallery.html

'''
模拟掷骰子3.0
'''
import random
import matplotlib.pyplot as plt

def roll_dice():
    """
        模拟掷骰子
    """
    roll = random.randint(1, 6)
    return roll

def main():
    """
        主函数
    """
    total_times = 100

    # 初始化列表 [0, 0, 0, 0, 0, 0]
    result_list = [0] * 11

    # 初始化点数列表
    roll_list = list(range(2, 13))
    roll_dict = dict(zip(roll_list, result_list))

    # 记录骰子的结果
    roll1_list = []
    roll2_list = []

    for i in range(total_times):
        roll1 = roll_dice()
        roll2 = roll_dice()

        roll1_list.append(roll1)
        roll2_list.append(roll2)

        for j in range(2, 13):
            if (roll1 + roll2) == j:
                roll_dict[j] += 1

    for i, result in roll_dict.items():
        print('点数{}的次数:{},频率:{}'.format(i, result, result / total_times))

    # 数据可视化
    x = range(1, total_times + 1)
    plt.scatter(x, roll1_list, c='red', alpha=0.5)
    plt.scatter(x, roll2_list, c='green', alpha=0.5)
    plt.show()

if __name__ == '__main__':
    main()

测试结果:

点数2的次数:3,频率:0.03
点数3的次数:5,频率:0.05
点数4的次数:8,频率:0.08
点数5的次数:8,频率:0.08
点数6的次数:20,频率:0.2
点数7的次数:10,频率:0.1
点数8的次数:12,频率:0.12
点数9的次数:13,频率:0.13
点数10的次数:10,频率:0.1
点数11的次数:9,频率:0.09
点数12的次数:2,频率:0.02

模拟掷骰子4.0





'''
模拟掷骰子4.0
'''
import random
import matplotlib.pyplot as plt

# 解决中文显示问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

def roll_dice():
    """
        模拟掷骰子
    """
    roll = random.randint(1, 6)
    return roll

def main():
    """
        主函数
    """
    total_times = 10000

    # 记录骰子的结果
    roll_list = []

    for i in range(total_times):
        roll1 = roll_dice()
        roll2 = roll_dice()
        roll_list.append(roll1 + roll2)

    # 数据可视化
    plt.hist(roll_list, bins=range(2, 14), normed=1, edgecolor='black', linewidth=1)
    plt.title('骰子点数统计')
    plt.xlabel('点数')
    plt.ylabel('频率')
    plt.show()

if __name__ == '__main__':
    main()

测试结果:

模拟掷骰子5.0







'''
模拟掷骰子5.0
'''
import matplotlib.pyplot as plt
import numpy as np

# 解决中文显示问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

def main():
    """
        主函数
    """
    total_times = 10000

    # 记录骰子的结果
    roll1_arr = np.random.randint(1, 7, size=total_times)
    roll2_arr = np.random.randint(1, 7, size=total_times)
    result_arr = roll1_arr + roll2_arr

    hist, bins = np.histogram(result_arr, bins=range(2, 14))
    print(hist)
    print(bins)

    # 数据可视化
    plt.hist(result_arr, bins=range(2, 14), normed=1, edgecolor='black', linewidth=1, rwidth=0.8)

    # 设置x轴坐标点显示
    tick_labels = ['2点', '3点', '4点', '5点',
                   '6点', '7点', '8点', '9点', '10点', '11点', '12点']
    tick_pos = np.arange(2, 13) + 0.5
    plt.xticks(tick_pos, tick_labels)

    plt.title('骰子点数统计')
    plt.xlabel('点数')
    plt.ylabel('频率')
    plt.show()

if __name__ == '__main__':
    main()

测试结果:

[ 269 559 798 1114 1363 1693 1413 1114 872 524 281]
[ 2 3 4 5 6 7 8 9 10 11 12 13]

posted on 2019-02-21 16:48  咘雷扎克  阅读(635)  评论(0编辑  收藏  举报

导航