【问题标题】:poisson arrival code in c++ gives same resultc ++中的泊松到达代码给出相同的结果
【发布时间】:2013-07-19 12:21:06
【问题描述】:

您好,我正在尝试模拟一些作业调度算法,并且我正在尝试为请求创建泊松到达函数。 我在维基百科上找到了泊松到达算法,我实现并运行了它,但我一直得到相同的结果(例如 l=15 -> 返回 14 , l=1/15 返回 0)

#include <cmath>
#include <iostream>
#include <cstdlib>
using namespace std;
main (){
for (int i=0;i<1000;i++)
{

float l=25;
float L=exp(-l);
float k=0;
float p=1;
//begin while
do{ 
k=k+1;
// Generate a random number between 0 and 1
// return a uniform number in [0,1].
double u = rand() / (double)RAND_MAX;   
p=p*u;
}   while (p>L);    
return k-1;
}}

这是我用来创建这个的算法

algorithm poisson random number (Knuth):
init:
     Let L ← e−λ, k ← 0 and p ← 1.
do:
     k ← k + 1.
     Generate uniform random number u in [0,1] and let p ← p × u.
while p > L.
return k − 1.

提前致谢

【问题讨论】:

    标签: c++ algorithm random simulate poisson


    【解决方案1】:

    您的问题有点不清楚,但我认为您的问题是每次运行程序时都期望不同的随机数。请注意,每次运行程序时 rand() 都会生成相同的随机数序列,除非您为其提供某种种子值。

    执行此操作的标准方法是使用当前时间播种随机数生成器,如下所示。

    #include <iostream>
    #include <ctime>
    #include <cstdlib>
    
    int main() {
        srand(time(NULL));
        std::cout << rand();
    
        return 0;
    }
    

    这将每次产生不同的随机序列。如果要删除 srand(time(NULL)) 行,每次运行程序都会得到相同的结果。

    您只需要在程序开始时调用 srand(time(NULL)) 一次。

    编辑:我还将编辑我的帖子,提到 C++11 中有一个专用的“随机”标头,我还没有使用过这个,所以我不能对此发表太多评论,但是你可以在这里阅读它

    http://www.cplusplus.com/reference/random/

    【讨论】:

    • r.e.你之前的评论。只有当您有 15 个代表时,您才能对答案进行投票。但是,如果答案是正确的,您可以单击帖子声誉下的勾号以接受答案
    猜你喜欢
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多