小循环,将决定需要多少试验才能获得成功?

2024-04-19 19:31:32 发布

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

基本上,用户将输入获得成功的概率p=.34,那么如何确定获得成功所需的试验次数呢?你知道吗

我知道我可以通过n+=1这样的计数器来得到试验次数,但不知道如何使用这个概率值。我们将不胜感激。你知道吗


Tags: 用户计数器概率次数
1条回答
网友
1楼 · 发布于 2024-04-19 19:31:32

您可以使用random()模块中的random来生成范围为[0,1]的浮点值。然后您可以将该值与用户输入的概率进行比较。如果随机值小于用户给定的概率,您就成功了。你知道吗

一旦你明白了这一点,你所需要的就是一个简单的while循环,它会一直生成数字,直到你成功为止。你知道吗

下面是一个函数的示例,它可以执行您想要的操作:

import random

# The function you wanted

def run_trials(p):
    '''only accepts int or float in range [0.0, 1.0]'''       
    # Count trials
    num_trials = 1
    while True:
        r = random.random()
        if r <= p:
            print "This took", num_trials, "trial(s) to get a success."
            break
        else:
            num_trials += 1


#Input
while True: 
    p = input("Please enter a probability: ")
    if isinstance(p, float) or isinstance(p, int):
        if 0 <= p <= 1:
            break     
run_trials(p) # pass it to the function

相关问题 更多 >