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