#include "TRandom.h"
#include "TGraphErrors.h"

const double TWOPI=2*acos(-1.);

//---------------------------------------------------
double normal(double sigma, double mu, double x)
//---------------------------------------------------
{
  return (1/sqrt(TWOPI)/sigma)*exp(-(x-mu)*(x-mu)/2/sigma/sigma);
}

void NormalConvergence()
{
  double rnd;
  int Nthrows=50000;
  int Ntotal = 300;
  int Noffset = 10;
  int Nbins = 61;
  float p=0.15;


  TH1F *data = new TH1F("data","",Nbins,Noffset-0.5,Noffset+Nbins-0.5);
  TH1F *Normal = new TH1F("Normal","",Nbins,Noffset-0.5,Noffset+Nbins-0.5);
  int nblue;
  int counter=0;
  for (int it=0;it!=Nthrows;it++) {
    nblue=0;
    for (int i=0;i!=Ntotal;i++)
      {      
	rnd=rand()/2147483647.;
	if (rnd<p) nblue++;
      }	
    //    cout << nblue << endl;
    data->Fill(nblue);
  }

  float prob=0.;
  for (int i=0; i!=Nbins; i++)
    {
      Normal->SetBinContent(i+1,normal(sqrt(p*(1-p)*Ntotal),p*Ntotal,i+Noffset));
      cout << sqrt(p*(1-p)*Ntotal) << "   " << p*Ntotal << "  " << i << "  " << normal(sqrt(p*(1-p)*Ntotal),p*Ntotal,i) << endl;
    }    

  gROOT->SetStyle("Plain");
  gStyle->SetCanvasColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetPadBorderMode(0);
  gStyle->SetPadColor(0);
  gStyle->SetLineWidth(1.);
  gStyle->SetCanvasDefH(596);
  gStyle->SetCanvasDefW(596);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetPadBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetTitleBorderSize(0);
  gStyle->SetStatBorderSize(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetPalette(1);
  gStyle->SetOptStat(0);
  
  c0 = new TCanvas("c0", "", 0, 0, 600, 450);
  c0->SetLeftMargin(0.12);
  c0->SetRightMargin(0.12);
  c0->SetBottomMargin(0.2);
  
  data->GetYaxis()->SetTitleOffset(1.5);
  data->GetXaxis()->SetTitle("Number of Blue Balls");
  data->GetYaxis()->SetTitle("Throws");
  data->SetMarkerStyle(20);
  data->SetMarkerColor(2);
  data->SetMarkerSize(1.);
  data->Draw("ep");  

  Normal->Scale(Nthrows);
  Normal->SetMarkerStyle(20);
  Normal->SetMarkerColor(3);
  Normal->SetMarkerSize(1.);
  Normal->Draw("same");  




  //  data->Fit("gaus");
  cout << "Number of Blue balls Mean/RMS/Error " <<  data->GetMean() << "   " << data->GetRMS() << "  " << data->GetRMS()/sqrt(Nthrows) << endl;
  cout << "Probability  " <<  100*data->GetMean()/Ntotal << " +/-  " << 100*data->GetRMS()/sqrt(Nthrows)/Ntotal << " % " << endl;
}
