簡體   English   中英

無法在 python 3.x 中生成蒙特卡羅模擬的概率?

[英]Can not generate probability for Monte Carlo Simulation in python 3.x?

我在 python 中為蒙特卡羅模擬創建了一個高級 Python 隨機函數,我的代碼運行正常。 但是,我無法產生抽獎的概率:帽子上的 40 個球中有 2 個 - 藍色和 2 個 - 紫色球。 總球數為 40、10-紅色、10-藍色、10-黃色、10-紫色。 以下是我的代碼:

import numpy as np
RED, BLUE, YELLOW, PURPLE = 1,2,3,4

def create_hat_of_balls(N):
    hat = 10*['1'] + 10*['2'] + 10*['3'] + 10*['4']
    val = 0 
    for num in range(40):
        drawing = [random.choice(hat) for num in range(10)]
        prob = drawing.count('blue') == 2 and drawing.count('purple') == 2
    val += prob
    final_prob = val / N
    print(f"(Blue, Purple) probability: {100*final_prob}%") 
    return hat

hat = create_hat_of_balls(10)
print(hat)

結果

(Blue, Purple) probability: 0.0%
['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', 
'2', '2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', 
'4', '4', '4', '4']

我的概率是 0.0% 怎么辦?

非常感謝幫助。

您的代碼試圖以三種不同的方式表示顏色:

  • 作為數字1, 2, 3, 4
  • 作為字符串'1', '2', '3', '4'
  • 作為字符串'blue', 'purple'

問題是,當您執行drawing.count('purple')它返回 0,因為drawing不包含字符串'purple'任何實例 - 它包含像'4'這樣'4'字符串,因為那是您放入hat

你應該選擇一種表現形式,並堅持下去。

import numpy as np
RED, BLUE, YELLOW, PURPLE = 1, 2, 3, 4

def create_hat_of_balls(N):
    hat = [RED, BLUE, YELLOW, PURPLE] * 10
    val = 0 
    for num in range(40):
        drawing = [random.choice(hat) for num in range(10)]
        prob = drawing.count(BLUE) == 2 and drawing.count(PURPLE) == 2
        val += prob
    final_prob = val / N
    print(f"(Blue, Purple) probability: {100*final_prob}%") 
    return hat

hat = create_hat_of_balls(10)
print(hat)

我還修復了val += prob行上的縮進 - 您應該在循環內執行此操作以累積每次采樣的結果,而不僅僅是最后一次。

您的代碼仍然存在其他邏輯問題 - 您最后只使用N進行除法,並且您的函數中有一些10硬編碼實例,但我不確定應該將哪個(些)更改為N ,也許40應該以某種方式依賴於N

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM