fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4. #include <cmath>
  5.  
  6. #include "PoissonRandom.h"
  7.  
  8. using namespace std;
  9.  
  10. // simulation de v.a.r. uniforme sur ]0,1[ :
  11. inline double unif_rand() {
  12. return (rand() + 0.5)/(RAND_MAX + 1.0);
  13. }
  14.  
  15. class Alea {
  16. public:
  17. virtual double rand() const = 0;
  18. };
  19.  
  20. class AleaDiscret : public Alea {
  21. public:
  22. virtual double loi(int n) const = 0;
  23. virtual double rand() const;
  24. };
  25.  
  26. double AleaDiscret::rand() const {
  27. double y = unif_rand();
  28. int x = 0;
  29. double Fx = loi(0);
  30. while ( y > Fx ) {
  31. Fx += loi(++x);
  32. }
  33. return double(x);
  34. }
  35.  
  36. class Poisson : public AleaDiscret {
  37. double lambda;
  38.  
  39. double e_lbda;
  40. public :
  41. Poisson(double l = 1.0) : lambda(l) , e_lbda(exp(-l)) {}
  42. virtual double loi(int n) const {
  43. return e_lbda*pow(lambda,n)/tgamma(n+1);
  44. }
  45.  
  46. // plus rapide que AleaDiscret::rand()
  47. virtual double rand() const;
  48. };
  49.  
  50. double Poisson::rand() const {
  51. double x = 1;
  52. int n = -1;
  53. do {
  54. x *= unif_rand();
  55. ++n;
  56. } while ( x > e_lbda );
  57. return double(n);
  58. }
  59.  
  60. double moy(const Alea & a) {
  61. const int N = 1000;
  62. double s = 0.0;
  63. for (int n = 0 ; n < N ; ++n)
  64. s += a.rand();
  65. return s/N;
  66. }
  67.  
  68. void PoissonRandom(int durationNum, int poiNum, int totalNum) {
  69. double total=0;
  70. // double duration[100];
  71. double *duration = new double[durationNum];
  72. int tmp=0, num;
  73. // Poisson poi(12);
  74. Poisson poi(poiNum);
  75. srand(int(time(0)));
  76. do{
  77. duration[tmp]=poi.rand();
  78. total+=duration[tmp];
  79. tmp++;
  80. // }while(total<=50);
  81. }while(total<=totalNum);
  82.  
  83. for(int i=1; i<tmp; i++){
  84. duration[i]+=duration[i-1];
  85. }
  86. cout<<tmp<<endl;
  87. for(int i=0; i<tmp; i++){
  88. cout<<duration[i]<<endl;
  89. }
  90. delete[] duration;
  91. }
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty