您将获得一个函数rand(a,b),该函数将生成[a,b](含)之间的等概率随机数。使用给定的rand(a,b)生成3个具有概率P(x),P(y),P(z)的数x,y,z,使得P(x)+ P(y)+ P(z)= 1 )函数。
这个想法是利用提供的rand(a,b)的等概率特征。假设给定的概率为百分比形式,例如P(x)= 40%,P(y)= 25%,P(z)= 35%。 。
以下是详细步骤。
1)生成一个介于1到100之间的随机数。由于它们是等概率的,因此每个数字出现的概率为1/100。
2)以下是有关生成随机数“ r”的一些重要注意事项。
a)’r’小于或等于P(x),概率为P(x)/ 100。
b)’r’大于P(x)且小于或等于P(x)+ P(y),且P(y)/ 100。
c)’r’大于P(x)+ P(y)且小于或等于100(或P(x)+ P(y)+ P(z)),概率为P(z)/ 100。
C
// This function generates 'x' with probability px/100, 'y' with
// probability py/100 and 'z' with probability pz/100:
// Assumption: px + py + pz = 100 where px, py and pz lie
// between 0 to 100
int random(int x, int y, int z, int px, int py, int pz)
{
// Generate a number from 1 to 100
int r = rand(1, 100);
// r is smaller than px with probability px/100
if (r <= px)
return x;
// r is greater than px and smaller than or equal to px+py
// with probability py/100
if (r <= (px+py))
return y;
// r is greater than px+py and smaller than or equal to 100
// with probability pz/100
else
return z;
}
Python
import random
# This function generates 'x' with probability px/100, 'y' with
# probability py/100 and 'z' with probability pz/100:
# Assumption: px + py + pz = 100 where px, py and pz lie
# between 0 to 100
def random(x, y, z, px, py, pz):
# Generate a number from 1 to 100
r = random.randint(1, 100)
# r is smaller than px with probability px/100
if (r <= px):
return x
# r is greater than px and smaller than
# or equal to px+py with probability py/100
if (r <= (px+py)):
return y
# r is greater than px+py and smaller than
# or equal to 100 with probability pz/100
else:
return z
# This code is contributed by rohan07