Python编程概率大理石出包编码

2024-09-26 22:50:03 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,我是编程新手,但我似乎不会编写概率问题的代码。例如,我该如何编码? 一个盒子里有12个A型晶体管和18个B型晶体管。随机取出一个晶体管返回。这个过程是重复的。第二种选择的概率是A型,谢谢!在

这是我第一次尝试。在

from  scipy import stats as st
import numpy as np
import random

total=30
totalA=12
totalB=18

def transistor():
    return random.choice("A","B")

random.seed(0)
for _in range(30):
    try1=transistor()
    try2=transistor()

    if try1="A":
        prob1=totalA/total
    else:
        prob1=totalB/total

    if try2="A":
        prob2=totalA/total
    else:
        prob2=totalB/total   

    if try1=="A" and try2=="A"
     prob=2*totalA/total

Tags: importifasrandom概率elsetotal晶体管
1条回答
网友
1楼 · 发布于 2024-09-26 22:50:03

如果你试图运行一个模拟,这个代码将给你一个10000次试验的概率。每次都会产生不同的结果。试验越多,就越准确。正确的理论答案是0.24。在

import random

trials = 10000 # total number of trials
totalA = 12 # total number of A transistors
totalB = 18 # total number of B transistors

successes = 0 # variable keeping track of how many successful pulls there were

choicelist = list("A" * totalA + "B" * totalB) # list containing transitors to correct proportion

def transistor():
    return random.choice(choicelist) # pick a random transistor from list

for i in range(trials):
    try1 = transistor()
    try2 = transistor()
    if try1 == "A" and try2 == "B": # if first pull is type A and second is type B...
        successes += 1 # ...then it's successful
print float(successes) / trials # print out the proportion of successes to trials

相关问题 更多 >

    热门问题