更新时间:2023-11-28 14:39:52
您的问题很模糊,因为有许多随机分布,其中较低的数字比较高的数字更有可能.另外,说在 a 和 b 之间"这里同样含糊不清.这是许多示例之一,它以您要求的方式在闭区间 [a, b] 中生成一个随机整数:
Your question is vague as there are numerous random distributions in which lower numbers are more likely than higher numbers. Also, saying "between a and b" is likewise vague here. Here is one of many examples, which produces a random integer in the closed interval [a, b] in the manner you're asking for:
min(random.randint(a, b), random.randint(a, b))
这是另一个:
min(random.randint(a, b), random.randint(a, b), random.randint(a, b))
随着 random.randint(a, b)
越来越多,它们的最小值趋向于越来越集中在范围的下端.
With more and more random.randint(a, b)
, their minimum tends to be more and more concentrated towards the lower end of the range.
用户pjs"写了以下评论:
The user "pjs" wrote the following comment:
这两者都可以推广到相同的形式,k阶统计量的最小值,可以使用单个随机数生成,然后缩放到正确的范围:int(math.floor(a + (b - a + 1) * (1.0 - random.random()**(1.0/k))))
.当 k == 2
这有一个三角形分布,并且对于更高的 k
值,它变得越来越重于 a
.如果您想玩具有方差减少"的游戏,则基于单个随机数也使此方法适用于常见随机数或对立随机数.Monte Carlo sims 中的策略.
Both of those can be generalized to the same form, the minimum of k order statistics, which can be generated using a single random number and then scaled to the correct range:
int(math.floor(a + (b - a + 1) * (1.0 - random.random()**(1.0 / k))))
. Whenk == 2
this has a triangle distribution, and for higher values ofk
it becomes more and more heavily weighted towardsa
. Basing it on a single random number also makes this method amenable to common random numbers or antithetic random numbers if you want to play games with "variance reduction" strategies in Monte Carlo sims.
但是,这个公式存在问题.
However, there are issues with this formula.
random.random()**(1.0/k)
在 1 附近是病态的,对于大 k
接近 1code>,因此在从 1/2 到 1 比从 0 到 1/2 更粗糙的浮点算术中,可能存在精度问题".(Devroye,1986,非均匀随机变量生成,第 675 页).min(random.randint(a, b) for i in k)
for some integer k
大于 0.random.random()**(1.0 / k)
is ill-conditioned near 1 and approaches 1 for large k
, so that in floating-point arithmetic which is coarser from 1/2 to 1 than from 0 to 1/2, "there could be an accuracy problem" (Devroye, 1986, Non-Uniform Random Variate Generation, page 675).min(random.randint(a, b) for i in k)
for some integer k
greater than 0.