////////////////////////////////////////////////////////////////////// // an example code for esttimating the value of mean and sigma // of a gaussian distribution from data, using MCMC for likelihood // maximization // written for THEP SERC 2015 ////////////////////////////////////////////////////////////////////// void fit_gaus(int np=1000){ const int N = 10; const int chain_size = np; double xg[N],mean=0.0; //array to store the data, N normal distributed random numbers double mu_true = 5.0, sigma_true = 1.0, mu_max = 0.0, sigma_max = 0.0; double ll_max=-10000000; //generate data. N gaussian distributed random numbers for (int ii = 0; ii < N; ii++){ xg[ii]=gRandom->Gaus(mu_true, sigma_true); mean +=xg[ii]; cout<Uniform(mu_low, mu_up); sigma0 = gRandom->Uniform(sigma_low, sigma_up); // step 2: calculate the likelihood function p(D|theta0) for the point theta0 = (mu0,sigma0) double ll0 = 0; for (int ii=0; ii freq_theta; vector mu; vector sigma; vector ll; freq_theta.push_back(1.); mu.push_back(mu0); sigma.push_back(sigma0); ll.push_back(ll0); for (int jj = 0; jj < chain_size; jj++){ // step 3: generate a new random point using the proposal function mu1 = gRandom->Gaus(mu0,del_mu); //if the increment is outside the range of search in mu, generate again while ( mu1 > mu_up || mu1 < mu_low ) mu1 = gRandom->Gaus(mu0,del_mu); //similarly take a step in sigma sigma1 = gRandom->Gaus(sigma0, del_sigma); while (sigma1 > sigma_up || sigma1 < sigma_low) sigma1 = gRandom->Gaus(sigma0, del_sigma); //now the new point is theta1 = (mu1,sigma1) = (mu0+del_mu,sigma0+del_sigma) // step 4: calculate p(D|theta1), actually the log of it double ll1 = 0; for (int ii=0; iiUniform(0.,1.))<(ll1 - ll0)){ //print the old point data: cout<