numpy 有没有办法运行不同概率值的代码?

ttcibm8c  于 2022-11-23  发布在  其他
关注(0)|答案(1)|浏览(133)

我正在做一个概率问题。在我的代码中,当我输入红蓝弓箭手的概率时,代码运行得很好。

from IPython.core import history
rng = default_rng(42)

def trial(red,blue , red_accurcy = 1, blue_accurcy = 1, history = False ,debug = False):
    if history:
        red_history = [red]
        blue_history = [blue]
        
    if debug:
        print(f"Start:\t red = {red:3d} blue = {blue:3d}")
    while red and blue:
        p = np.array([red,blue] , dtype = float)
        p /= p.sum()
        arrow = rng.choice(['red' , 'blue'] , p=p)
        if arrow == 'red':
            blue -= 1 if rng.uniform() < red_accurcy else 0
        else:
            red -= 1 if rng.uniform() < blue_accurcy else 0
        if debug:
            print(f"\t red = {red:3d} blue = {blue:3d} arrow = {arrow}")
        
        if history:
            red_history.append(red)
            blue_history.append(blue)
        
    if debug:
        print(f"End:\t red = {red:3d} blue = {blue:3d}") 
    if history:    
        return red,blue, red_history, blue_history
    else:
        return red, blue ,red_accurcy ,blue_accurcy
trial(90,45,0.1,0.2)

输出量:

(60, 0, 0.1, 0.2)

现在,我试着为红色选择不同的概率,看看蓝色能否获胜:

red_ac = np.linspace(0,1,10)
battles = [trial(90,45,red_accurcy=red_ac,blue_accurcy= 1) for red_ac in range(10)]
battles

输出量:

[(0, 45, 0, 1),
 (75, 0, 1, 1),
 (82, 0, 2, 1),
 (80, 0, 3, 1),
 (78, 0, 4, 1),
 (74, 0, 5, 1),
 (69, 0, 6, 1),
 (74, 0, 7, 1),
 (81, 0, 8, 1),
 (81, 0, 9, 1)]

我看不太对。你能告诉我哪里出错了吗?

vfhzx4xs

vfhzx4xs1#

这个答案适用于上面的代码。

red_accurcy = np.linspace(0,1,10)
N = 10
n_max = 100
n_values = range(2,n_max)

simulate_results = []
for n in n_values:
    results = [trial(90,45,red_accurcy= r ,blue_accurcy= 1) for r in red_accurcy]

检查蓝色是否获胜

blue_win = [(red,blue,red_accurcy,blue_accurcy) for red,blue,red_accurcy,blue_accurcy in results if blue>0] 
blue_win

和输出:

[(0, 45, 0.0, 1),
 (0, 24, 0.1111111111111111, 1),
 (0, 11, 0.2222222222222222, 1)]

相关问题