我的rand(0,1)
php函数在我调用它时随机返回0
和1
。
我可以在php中定义一些东西吗?这样,对于随机调用,30%
的数字将是0
,70%
的数字将为1
?php有内置的函数吗?
当然。
$rand = (float)rand()/(float)getrandmax();
if ($rand < 0.3)
$result = 0;
else
$result = 1;
你也可以处理任意的结果和权重。
$weights = array(0 => 0.3, 1 => 0.2, 2 => 0.5);
$rand = (float)rand()/(float)getrandmax();
foreach ($weights as $value => $weight) {
if ($rand < $weight) {
$result = $value;
break;
}
$rand -= $weight;
}
您可以这样做:
$rand = (rand(0,9) > 6 ? 1 : 0)
rand(0,9)
会产生一个0到9之间的随机数,每当随机产生的数字大于6(应该是近70%的时间),它就会给你1
,否则0
。。。
显然,对我来说,这似乎是最简单的解决方案,但毫无疑问,它不会给你准确的1
70%的时间,但如果做得正确,应该很接近做到这一点。
但是,我怀疑任何基于rand
的解决方案都会给你1
整整70%的时间
生成一个介于1和100之间的新随机值。如果该值低于30,则使用0
,否则使用1
:
$probability = rand(1, 100);
if ($probability < 30) {
echo 0;
} else {
echo 1;
}
要测试这一理论,请考虑以下循环:
$arr = array();
for ($i=0; $i < 10000; $i++) {
$rand = rand(0, 1);
$probability = rand(1, 100);
if ($probability < 30) {
$arr[] = 0;
} else {
$arr[] = 1;
}
}
$c = array_count_values($arr);
echo "0 = " . $c['0'] / 10000 * 100;
echo "1 = " . $c['1'] / 10000 * 100;
输出:
0 = 29.33
1 = 70.67
创建一个包含70%1和30%0s的数组。然后随机排序。然后开始从数组的开头到末尾挑选数字:)
$num_array = array();
for($i = 0; $i < 3; $i++) $num_array[$i] = 0;
for($i = 0; $i < 7; $i++) $num_array[$i] = 1;
shuffle($num_array);
优点:对于任何这样的数组,您将分别获得30%0和70%1。
缺点:创建初始数组可能需要比仅使用rand()
的解决方案更长的计算时间。
我搜索问题的答案,这就是我找到的主题。但它并没有回答我的问题,所以我不得不自己解决,我做到了:)。
我想也许这也能帮助其他人。这是关于你的要求,但更多的用途。
基本上,我把它用作随机生成物品(比如武器)的"功率"计算器。该项目在数据库中有一个"最小功率"和一个"最大功率"值。我想有80%的机会让"功率"值接近物品最大可能功率的80%,20%接近最高可能功率的20%(存储在数据库中)。
因此,为了做到这一点,我做了以下操作:
$min = 1; // this value is normally taken from the db
$max = 30; // this value is normally taken from the db
$total_possibilities = ($max - $min) + 1;
$rand = random_int(1, 100);
if ($rand <= 80) { // 80% chances
$new_max = $max - ($total_possibilities * 0.20); // remove 20% from the max value, so you can get a number only from the lowest 80%
$new_rand = random_int($min, $new_max);
} elseif ($rand <= 100) { // 20% chances
$new_min = $min + ($total_possibilities * 0.80); // add 80% for the min value, so you can get a number only from the highest 20%
$new_rand = random_int($new_min, $max);
}
echo $new_rand; // this will be the final item power
您可能遇到的唯一问题是,初始$min
和$max
变量是否相同(或者很明显,如果$max
大于$min
)。这将抛出一个错误,因为随机的工作方式与($min, $max)
类似,而不是相反。
为了不同的目的,可以很容易地将此代码更改为具有更多的百分比,而不是将80%和20%设置为40%、40%和20%(或您需要的任何内容)。我认为代码非常容易阅读和理解。
如果这没有帮助,我很抱歉,但我希望是:)。无论哪种方式都不会造成任何伤害;)。