这是看起来工作,并符合所有规格(和主观上看起来很快)的东西。请注意,您的约束条件是第二个数字与第一个数字不相同,因此会将概率选择为关闭状态。这个问题被下面的代码有效地忽略了,它只是强制执行了限制(换句话说,第二个数字是将不是的概率是prob_list
中的每个数字给出的)。
import random
prob_list = [[1, 0.5], [2, 0.25], [3, 0.05], [4, 0.01], [5, 0.09], [6, 0.1]]
# create a list with the running total of the probabilities
acc = 0.0
acc_list = [acc]
for t in prob_list:
acc += t[1]
acc_list.append(acc)
TOLERANCE = .000001
def approx_eq(v1, v2):
return abs(v1-v2) <= TOLERANCE
def within(low, value, high):
""" Determine if low >= value <= high (approximately) """
return (value > low or approx_eq(low, value)) and \
(value < high or approx_eq(high, value))
def get_selection():
""" Find which weighted interval a random selection falls in """
interval = -1
rand = random.random()
for i in range(len(acc_list)-1):
if within(acc_list[i], rand, acc_list[i+1]):
interval = i
break
if interval == -1:
raise AssertionError('no interval for {:.6}'.format(rand))
return interval
def get_two_different_nums():
sel1 = get_selection()
sel2 = sel1
while sel2 == sel1:
sel2 = get_selection()
return prob_list[sel1][0], prob_list[sel2][0]
http://stackoverflow.com/questions/4265988/generate-random-numbers-with-a-given-numerical-distribution/ – khachik 2010-11-25 12:00:16