我需要编写一个代码来计算在大于0.99的值之前观察到的均匀分布随机数(0,1)的数量,而不使用WHILE循环。但我得到错误信息:'float'对象不能被解释为整数。有人知道问题在哪里吗?
import numpy as np
x = random.uniform(0,1)
count = 0
target = 0.99
for i in range(x):
x[i] = random.uniform(0,1)
if x[i] <= target:
count += 1
break
else:
continue
print('%d uniformly random numbers observed before observing af value larger than 0.99' % count)
使用for-loop
:
import itertools
import numpy as np
import random
count = 0
target = 0.99
for i in itertools.count(start=1):
x = random.uniform(0,1)
if x > target:
break
count += 1
print('%d uniformly random numbers observed before observing af value larger than 0.99' % count)
与while-loop
使用这个:
import numpy as np
import random
count = 0
target = 0.99
while 1:
x = random.uniform(0,1)
if x <= target:
count += 1
else:
break
print('%d uniformly random numbers observed before observing af value larger than 0.99' % count)
为什么不使用while循环呢?
import numpy as np
import random
count = 0
target = 0.99
x = random.uniform(0,1)
while x <= target:
count += 1
x = random.uniform(0,1)
print('%d uniformly random numbers observed before observing af value larger than 0.99' % count)