搜尋
首頁後端開發Python教學python知識分解析擲骰子遊戲

這篇文章給大家分享的內容是關於python知識分解析擲骰子遊戲 ,有著一定的參考價值,有需要的朋友可以參考一下。最近學習了點統計學及python知識,試著分析下擲骰子遊戲。骰子依標準6面,分析一次投1顆、2顆、3顆、4顆,投擲10、100、1000、10000次時的結果。

使用工具
 Jupyter Notebook 分析利器
matplotlib、pygal 視覺化套件

1、猜次數

1-6中每个数字出现的次数
# 导入包
import pygal
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号
from random import randint
# 利用随机数据模拟掷骰子
# 每次显示1-6中的一个数

num_sides = 6  # 骰子的6个面
def getData(N, times):
    """
    定义函数,获取投掷数据
    N: 表示一次用几个骰子投
    times:表示总共投几次
    """  
    results = []    
    for n in range(1,N+1):    
        for roll_num in range(times):
            result = randint(1,num_sides)
            results.append(result)    
        return results
# 打印投掷结果
print(getData(1,10)) # 1个骰子掷10次
print(getData(2,5))  # 2个骰子掷5次
[2, 2, 2, 2, 1, 6, 4, 4, 5, 5]
[4, 3, 5, 6, 2, 2, 3, 6, 4, 4]
# 分析结果# 统计每个数字出现的次数并显示图片
    # N: 表示一次用几个骰子投
    # data 表示投掷数据def showResult(N, times):
    frequencies = []    for value in range(1, num_sides+1):
        frequency = getData(N, times).count(value)
        frequencies.append(frequency)    # 数据可视化
    # 本次利用 pygal 生成SVG格式矢量图
    hist = pygal.Bar()
    hist.title = str(N)+"个骰子掷"+ str(times) +"次的结果"
    hist.x_labels = ['1','2','3','4','5','6']
    hist.x_title = "点数"
    hist.y_title = "出现次数"

    hist.add(str(N)+'骰子', frequencies)
    hist.render_to_file('1-'+str(N)+str(times)+'.svg') # 储存为矢量图
# 一个骰子掷10,100, 1000, 10000次结果分析showResult(1,10)
showResult(1,100)
showResult(1,1000)
showResult(1,10000)

python知識分解析擲骰子遊戲##

# 2个骰子掷10,100, 1000, 10000次结果分析showResult(2,10)
showResult(2,100)
showResult(2,1000)
showResult(2,10000)

python知識分解析擲骰子遊戲

3個骰子、4個骰子就不再截圖了。

我們發現在投擲的次數越多,每個數出現的機率越接近,最後趨向於相同。

2、猜大小

每次投掷点数和
# 每次投掷点数和def getData2(N, times):
    """
    定义函数,获取投掷数据
    N: 表示一次用几个骰子投
    times:表示总共投几次
    """  
    results = []    for roll_num in range(times):
        result = 0
        for n in range(1,N+1):
            result += randint(1,num_sides)
        results.append(result)    
    return results
# 打印投掷结果print(getData2(1,10)) # 1个骰子掷10次print(getData2(2,5))  # 2个骰子掷5次
[4, 3, 6, 2, 5, 4, 5, 3, 6, 2]
[6, 10, 5, 8, 7]
# 分析结果# 统计数字和出现的次数并显示图片
    # N: 表示一次用几个骰子投
    # data 表示投掷数据def showResult2(N, times):
    frequencies = []    for value in range(N, N*num_sides+1):
        frequency = getData2(N, times).count(value)
        frequencies.append(frequency)    # 数据可视化
    # 本次利用 matplotlib 生成图片
    x_num = N*num_sides+1-N
    idx = np.arange(x_num)
    width = 0.5
    sn = str(N)
    sm = str(times)
    x_labels = [str(n) for n in range(N, N*num_sides+1)]  # X轴刻度

    plt.bar(idx, frequencies, width, color='red', label=sn+'个骰子')
    plt.xlabel('点数和')
    plt.ylabel('出现次数')
    plt.title(sn+'个骰子投掷'+ sm +'次的结果')
    plt.xticks(idx, x_labels)
    plt.legend()  # 显示图例
    plt.show()

1顆骰子猜大小沒什麼意義,我們直接來分析兩個骰子的狀況。

#  2个骰子掷10,100, 1000, 10000次结果分析showResult2(2,10)
showResult2(2,100)
showResult2(2,1000)
showResult2(2,10000)

python知識分解析擲骰子遊戲

#  3个骰子掷10,100, 1000, 10000次结果分析showResult2(3,10)
showResult2(3,100)
showResult2(3,1000)
showResult2(3,10000)

python知識分解析擲骰子遊戲

#  4个骰子掷10,100, 1000, 10000次结果分析showResult2(4,10)
showResult2(4,100)
showResult2(4,1000)
showResult2(4,10000)

python知識分解析擲骰子遊戲

從上面幾圖中我們可以看到,當投擲次數足夠多時,出現大/小點數出現的機率基本上相同,點數大小呈現常態分佈的特徵。

相關推薦:

擲骰子遊戲-C語言實作

擲骰遊戲

C 擲骰子遊戲

練手小程序:craps擲骰子遊戲

#擲骰問題

以上是python知識分解析擲骰子遊戲的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在Python陣列上可以執行哪些常見操作?在Python陣列上可以執行哪些常見操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些類型的應用程序中,Numpy數組常用?在哪些類型的應用程序中,Numpy數組常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什麼時候選擇在Python中的列表上使用數組?您什麼時候選擇在Python中的列表上使用數組?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。

您如何在python列表中訪問元素?您如何在python列表中訪問元素?Apr 26, 2025 am 12:03 AM

toAccesselementsInapythonlist,useIndIndexing,負索引,切片,口頭化。 1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具