Skip to content

Instantly share code, notes, and snippets.

@luxixing
Created November 13, 2013 15:34
Show Gist options
  • Save luxixing/7450993 to your computer and use it in GitHub Desktop.
Save luxixing/7450993 to your computer and use it in GitHub Desktop.
权重概率计算
<?php
$w = array('a' =>1, 'b'=>10, 'c'=>14, 'e'=>20, 'f'=>30, 'h'=>6, 'g'=>70);
function roll($weight)
{
$sum = array_sum($weight);
$j = 0;
foreach($weight as $k=>$v)
{
$j = mt_rand(1,$sum);
if($j <= $v)
{
return $k;
}else{
$sum -= $v;
}
}
}
$ret = array();
$n = 1000;
for($i=0;$i<$n;$i++)
{
$v = roll($w);
$ret[$v] = isset($ret[$v]) ? $ret[$v] + 1 :1;
}
print_r($ret);
foreach($ret as $k=>$v)
{
printf("real: %f\t", ($v / $n));
printf("set: %f\n",($w[$k] / array_sum($w)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment