我是新来的:) 我试图在PHP中创建一个非均匀的随机分布代码,其中包含以下小数概率(精度2)
From 1.10 to 1.15 = 40%
From 1.16 to 1.20 = 30%
From 1.21 to 1.25 = 20%
From 1.26 to 1.30 = 10%
这是我的实际代码:
$low = 1.1
$high = 1.3
$multiplier = mt_rand($low*100,$high*100)/100;
这不会返回所需的分布。如何更改我的代码以使其在分发中不均匀?
答案 0 :(得分:2)
您可以分两步完成此操作:
$chance = rand(1,100);
switch(true) {
case ($chance <= 40):
// 40% 1.10 - 1.15
echo 1+rand(10,15)/100;
break;
case ($chance <= 70):
// 30% 1.16 - 1.20
echo 1+rand(16,20)/100;
break;
case ($chance <= 90):
// 20% 1.21 - 1.25
echo 1+rand(21,25)/100;
break;
default:
// 10% 1.26 - 1.30
echo 1+rand(26,30)/100;
break;
}
运行10'000'000次,给出以下百分比:
From 1.10 to 1.15 = 40.00223%
From 1.16 to 1.20 = 29.99841%
From 1.21 to 1.25 = 20.00157%
From 1.26 to 1.30 = 9.99779%
更新:更新为icio Recommended