0

我想知道在 0 到 10 之间的随机值大于 8 之前已经进行了多少次尝试。我有以下代码可以正常工作:

import numpy as np

x = np.random.uniform(low=0, high=10, size=1)
attempt = 1

while(x < 8):
    attempt = attempt + 1
    x = np.random.uniform(low=0, high=10, size=1)

但是,现在我想第四次获得 x 大于 8 之前的尝试次数。为此,我将 for 循环放置在 while 循环之前,如下所示:

for i in range(0,4):
    while(x < 8):
        attempt = attempt + 1
        x = np.random.uniform(low=0, high=10, size=1)

但是,这并没有按我的预期工作。有人可以帮我解决这个问题吗?

4

5 回答 5

2

您想获得8在 4 个连续跟踪中获得随机数所需的总尝试次数。尝试这个:

>>> import numpy as np
>>> def fun():
...     x = np.random.uniform(0,10,1)
...     attempt = 1
...     while x<8:
...             attempt += 1
...             x = np.random.uniform(0,10,1)
...     return attempt 
>>> for i in range(0,4):
...     print("Trial" , i , "took" , fun(), "Attempts")

输出:

Trial 0 took 1 Attempts
Trial 1 took 1 Attempts
Trial 2 took 8 Attempts
Trial 3 took 3 Attempts
于 2019-02-06T05:56:02.023 回答
0

问题是你没有重置你的 x 值。因此,一旦将变量设置为大于 8 的值,您的代码将不会再次进入 while 循环。您需要在 while 循环之前设置 x = 0。

于 2019-02-06T05:49:10.487 回答
0

您应该将代码修改为

for i in range(0,4):
    x = np.random.uniform(low=0, high=10, size=1)
    while(x < 8):
        attempt = attempt + 1
        x = np.random.uniform(low=0, high=10, size=1)

这将在 x 进入while循环之前重置它。如果没有此语句,您的控件将仅进入一次 while 循环。

于 2019-02-06T05:50:07.283 回答
0

有很多方法可以做到这一点。下面应该工作...

import numpy as np

successes = 0
rolls = 0
while (successes < 4):
    x = np.random.uniform(low=0, high=10, size=1)
    rolls += 1
    if x > 8:
        successes += 1

print(rolls)
于 2019-02-06T05:50:55.320 回答
0

这不是一个for loop案例。尝试这个:

while x < 8 and i <= 4:
    x = np.random.uniform(low=0, high=10, size=1)
    if x>8:
        i+=1
        x=np.random.uniform(low=0, high=10, size=1)
        attempt = 1
    print(attempt, x)
    attempt = attempt + 1
于 2019-02-06T05:52:00.117 回答