Created
November 13, 2013 15:34
-
-
Save luxixing/7450993 to your computer and use it in GitHub Desktop.
权重概率计算
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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