[問題] 想請教function的問題
抱歉~
又來請教function的問題 (使用C++)
要做一個普瓦松的隨機數據
已在網路上找到一個樣本
但我想把這個程式做成一個function
因為我最主要的程式 會一直使用這個反覆產生隨機數值
但是在main()前面 一堆class 一堆function
搞得頭都昏了 試了很多次 還是沒辦法 (實在是太肉腳)
只好來請教各位高手~
程式碼網址 : http://ideone.com/XkMQH
=========================== 以下是程式碼
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include<fstream>
#include<iomanip>
using namespace std;
// simulation de v.a.r. uniforme sur ]0,1[ :
inline double unif_rand() {
return (rand() + 0.5)/(RAND_MAX + 1.0);
}
class Alea {
public:
virtual double rand() const = 0;
};
class AleaDiscret : public Alea {
public:
virtual double loi(int n) const = 0;
virtual double rand() const;
};
double AleaDiscret::rand() const {
double y = unif_rand();
int x = 0;
double Fx = loi(0);
while ( y > Fx ) {
Fx += loi(++x);
}
return double(x);
}
class Poisson : public AleaDiscret {
double lambda;
double e_lbda;
public :
Poisson(double l = 1.0) : lambda(l) , e_lbda(exp(-l)) {}
virtual double loi(int n) const {
return e_lbda*pow(lambda,n)/tgamma(n+1);
}
// plus rapide que AleaDiscret::rand()
virtual double rand() const;
};
double Poisson::rand() const {
double x = 1;
int n = -1;
do {
x *= unif_rand();
++n;
} while ( x > e_lbda );
return double(n);
}
double moy(const Alea & a) {
const int N = 1000;
double s = 0.0;
for (int n = 0 ; n < N ; ++n)
s += a.rand();
return s/N;
}
int main(){
double total=0;
double duration[100]; //這個100的數值可修改
int tmp=0, num;
Poisson poi(12); //這個12的數值可修改
srand(int(time(0)));
do{
duration[tmp]=poi.rand();
total+=duration[tmp];
tmp++;
}while(total<=50); //這個50的數值可修改
for(int i=1; i<tmp; i++){
duration[i]+=duration[i-1];
}
cout<<tmp<<endl;
for(int i=0; i<tmp; i++){
cout<<duration[i]<<endl;
}
return 0;
}
實在是做不出來 只好來請教
謝謝您~~
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.116.243.66
※ 編輯: ieck 來自: 140.116.243.66 (02/01 17:55)
※ 編輯: ieck 來自: 140.116.243.66 (02/01 17:58)
→
02/01 18:07, , 1F
02/01 18:07, 1F
→
02/01 18:10, , 2F
02/01 18:10, 2F
→
02/01 18:10, , 3F
02/01 18:10, 3F
→
02/01 18:32, , 4F
02/01 18:32, 4F
→
02/01 18:35, , 5F
02/01 18:35, 5F
→
02/01 19:12, , 6F
02/01 19:12, 6F
→
02/01 19:33, , 7F
02/01 19:33, 7F
→
02/01 19:45, , 8F
02/01 19:45, 8F
→
02/01 19:46, , 9F
02/01 19:46, 9F
→
02/01 19:46, , 10F
02/01 19:46, 10F
→
02/01 19:48, , 11F
02/01 19:48, 11F
→
02/01 19:50, , 12F
02/01 19:50, 12F
→
02/01 19:56, , 13F
02/01 19:56, 13F
→
02/01 19:57, , 14F
02/01 19:57, 14F
→
02/01 19:58, , 15F
02/01 19:58, 15F
→
02/01 19:58, , 16F
02/01 19:58, 16F
→
02/01 19:59, , 17F
02/01 19:59, 17F
→
02/01 19:59, , 18F
02/01 19:59, 18F
→
02/01 20:00, , 19F
02/01 20:00, 19F
→
02/01 20:01, , 20F
02/01 20:01, 20F
→
02/01 20:01, , 21F
02/01 20:01, 21F
→
02/01 20:11, , 22F
02/01 20:11, 22F
→
02/01 20:12, , 23F
02/01 20:12, 23F
→
02/01 20:29, , 24F
02/01 20:29, 24F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):