Python编程概率大理石从包编码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python编程概率大理石从包编码相关的知识,希望对你有一定的参考价值。
嘿,我是编程新手,但似乎无法对概率问题进行编码。例如,我将如何编码?一个盒子包含12个A型晶体管和18个B型晶体管。随机取出一个晶体管并返回。重复该过程。确定第一个选择的是A型,第二个是B型的概率。谢谢!
这是我的第一次尝试。
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
答案
如果您正在尝试运行模拟,此代码将为您提供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
以上是关于Python编程概率大理石从包编码的主要内容,如果未能解决你的问题,请参考以下文章