- #1
Amrator
- 246
- 83
I'm trying to write a C++ program to generate random numbers using the acceptance-rejection method. To plot the graphs, I'm using ROOT by CERN. I am checking if y values taken from the rectangular boundary are less than or equal to the function ##f(x_{i}) = e^{-k(x_{i} - x_{0})^{2}}##.
I am not sure I am even coding the method correctly. May I have some guidance?
C++:
void rejection()
{
int n = 100;
float x, y;
float pi = TMath::Pi();
float squeeze = 1.;
float A = 1.0/sqrt(2.*pi);
cout << "Amplitude: " << A << endl;
gStyle->SetOptStat(0);
TH1D *dist = new TH1D("dist", "sampling", 100, -4, 100);
TF1 *f = new TF1("f", "exp(-1000.*(x-0.3)*(x-0.3))", 0, 1);
for (int i = 0; i < n; i++)
{
x = gRandom->Rndm();
y = gRandom->Rndm();
if(y <= f)
{
dist->Fill(x); //accept x
}
}
float scale = A/dist->GetMaximum();
float scale = 1./dist->GetMaximum();
dist->Scale(scale);
dist->Draw("same");
}
I am not sure I am even coding the method correctly. May I have some guidance?
Last edited: