3

我正在尝试根据泊松到达创建一个随机的“hello world”函数。在下面的代码中,我定义平均平均值(Lamda)为 5。我希望时间从 1 到 5 秒过去,并跟踪它。

基于一个开源项目,这张图片中的seagull herehere,我可以同时看到,但不同的意思是,流量的随机出现越多(在我的例子中,“hello world”)。但就我而言,它只是随机睡眠时间,但 Hello World 的数量是相同的。

如何根据我上面使用的图像来实现这个想法。这是为随机生成器进行泊松分布的正确方法吗?我看到了基于Knuth的 Poisson 算法

谢谢你的帮助..对不起我的英语不好。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <string.h>
#include <time.h>

int poisson(double lambda){
  int k=0;
  double L=exp(-lambda), p=1;
  do {
    ++k;
    p *= rand()/(double)INT_MAX;
  } while (p > L);
  return --k;
}

int main()
{
int i=0; 
int val=0;
time_t timer;
char buffer[25];
struct tm* val_time;



    /*For time= 0 until time=10*/
    for  (i=0; i<10; i++)
    {
    printf("Hello World\n");

    /*To print the time*/
    time(&timer);
    val_time = localtime(&timer);
    strftime(buffer, 25, "%Y:%m:%d%H:%M:%S", val_time);
    puts(buffer);

    sleep(poisson(2)); /*interarrival process*/
    }

}
4

2 回答 2

1

给定您的代码,您将始终打印 10 次消息。似乎您需要检查您的总时间是否在循环开始时经过,如果是,则中断循环。给你一个想法:

time_t before, timer;
...
time(&before);
for (...) {
    time(&timer);
    if (time - before > timeout) {
         break;
    }
    before = timer;
    ...
}
于 2011-11-30T20:17:47.893 回答
1

我认为 INT_MAX 是错误的,请这样做:

    p *= rand()/(double)RAND_MAX;

此外,只要循环以 10 为界,您就不会得到更多的问候。你能指望什么?

这是我完整的 C++11(不是 C!)版本的程序:

在https://ideone.com/viZi3上实时查看(请注意Time limit exceeded,由于 IdeOne 上存在明显的时间限制,它会在此处出现软故障)

#include <iostream>
#include <random>
#include <chrono>
#include <iomanip>

static std::mt19937 rng;
static std::poisson_distribution<int> poisson(2.0);

typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::time_point<Clock> Time;

int main()
{
    const Time finish_pole = Clock::now() + std::chrono::seconds(10);

    for (Time now = Clock::now(); now <= finish_pole; now = Clock::now())
    {
        std::cout << "Hello World\n";

        std::time_t now_c = Clock::to_time_t(now);
#if CXX11_SUPPORT_COMPLETE
        std::cout << std::put_time(std::localtime(&now_c), "%F %T") << std::endl;
#else
        char buffer[25];
        strftime(buffer, 25, "%Y:%m:%d%H:%M:%S", localtime(&now_c));
        std::cout << buffer << std::endl;
#endif

        sleep(poisson(rng)); /*interarrival process*/
    }

}
于 2011-11-30T20:19:59.087 回答