首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP概率分布函数

PHP概率分布函数
EN

Stack Overflow用户
提问于 2014-05-16 08:43:00
回答 2查看 864关注 0票数 0

有人知道概率分布的函数吗?

假设我有一个数组:

代码语言:javascript
复制
$arr = array(
    'A' => 100, 
    'B' => 200, 
    'C' => 300, 
    'D' => 400
);

我正在寻找的函数可以输出像A=97,B=203,C=312,D=388这样的东西,而不需要做1000次迭代。有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2017-01-24 22:20:09

该数组为$image,$Lg是离散可能值的个数

代码语言:javascript
复制
    $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]);
        }
    }
票数 0
EN

Stack Overflow用户

发布于 2014-05-16 09:45:00

以前有人这么做过。跟着tut走,它帮了我大忙。

以下是我对此的看法:

代码语言:javascript
复制
<?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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23690914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档