PHP概率分布函数

时间:2014-05-16 00:43:00

标签: php statistics probability

有没有人知道概率分布函数?

说我有一个数组:

$arr = array(
    'A' => 100, 
    'B' => 200, 
    'C' => 300, 
    'D' => 400
);

我正在寻找输出类似A = 97,B = 203,C = 312,D = 388而不必进行1000次迭代的函数。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

数组是$ image, $ Lg是离散可能值的数量

    $n_element=count($image);
    $cdf_array=array_fill(0,$Lg,0);
    for($i=0;$i<$n_element;$i++){
        $cdf_array[$image[$i]-1]=$cdf_array[$image[$i]-1]+1;
    }
    $cdf_array=array_filter($cdf_array,function($var){return $var!=0;});
    $keys=array_keys($cdf_array);
    $cdf_min=$cdf_array[$keys[0]];

    $not_null_el=count($keys);
    for($i=0;$i<$not_null_el;$i++){
        $cdf_array[$keys[$i]]=array_sum(array_chunk($cdf_array,$i+1,1)[0]);
        }
    }

答案 1 :(得分:-1)

之前有人这样做过。跟着啧啧,它帮了我。

继承了我的看法:

<?php
class WeightedRandom
{
    private $generated;
    private $weights;
    private $items;

    public function __construct( array $weights, array $items  )
    {

        $this->weights = $weights;
        $this->items = $items;

    }

    public function RandomNumber( int $min, int $max )
    {
        return mt_rand() * ( $max - $min ) + $max;
    }

    public function Generate()
    {
        $totalWeight = array_sum( $this->weights );
        $randomNum = $this->RandomNumber(0, $totalWeight);
        $weightSum = 0;
        $itemCount = count($this->items);
        $item;
        $i;

        for ( $i = 0; $i < $itemCount; $i++ ) 
        {
            $weightSum += $this->weights[$i];

            if ( $randomNum <= $weightSum )
            {
                $item = $this->items[$i];
                break;
            }
        }

        return $item;

    }

    /*
    public function Generate()
    {
        $weightedList = [];
        $multiples;
        $i;
        $j;
        $weightCount;

        for( $i = 0; $i < $weightCount; $i++ )
        {
            $multiples = $this->weights[$i] * 10;

            for( $j = 0; $j < $multiples; $j++)
            {
                array_push($weightedList, $this->items[$i]);
            }
        }

        return $weightedList;
    }
    */
}
?>

Source and tutorial