binomial.C

Go to the documentation of this file.
00001 // tutorial illustrating the use of TMath::Binomial
00002 //  can be run with:
00003 // root > .x binomial.C
00004 // root > .x binomial.C+ with ACLIC
00005 //Author: Federico Carminati
00006    
00007 #include <TMath.h>
00008 #include <TRandom.h>
00009 
00010 void binomialSimple() {
00011   //
00012   // Simple test for the binomial distribution
00013   //
00014   printf("\nTMath::Binomial simple test\n");
00015   printf("Build the Tartaglia triangle\n");
00016   printf("============================\n");
00017   const Int_t max=13;
00018   Int_t j;
00019   for(Int_t i=0;i<max;i++) {
00020     printf("n=%2d",i);
00021     for(j=0;j<(max-i);j++) printf("  ");
00022     for(j=0;j<i+1;j++) printf("%4d",TMath::Nint(TMath::Binomial(i,j)));
00023     printf("\n");
00024   }
00025 }
00026 
00027 void binomialFancy() {
00028   Double_t x;
00029   Double_t y;
00030   Double_t res1;
00031   Double_t res2;
00032   Double_t err;
00033   Double_t serr=0;
00034   const Int_t nmax=10000;
00035   printf("\nTMath::Binomial fancy test\n");
00036   printf("Verify Newton formula for (x+y)^n\n");
00037   printf("x,y in [-2,2] and n from 0 to 9  \n");
00038   printf("=================================\n");
00039   TRandom r;
00040   for(Int_t i=0; i<nmax; i++) {
00041     do {
00042         x=2*(1-2*r.Rndm());
00043         y=2*(1-2*r.Rndm());
00044     } while (TMath::Abs(x+y)<0.75); //Avoid large cancellations
00045     for(Int_t j=0; j<10; j++) {
00046        res1=TMath::Power(x+y,j);
00047        res2=0;
00048        for(Int_t k=0; k<=j; k++)
00049           res2+=TMath::Power(x,k)*TMath::Power(y,j-k)*TMath::Binomial(j,k);
00050        if((err=TMath::Abs(res1-res2)/TMath::Abs(res1))>1e-10)
00051               printf("res1=%e res2=%e x=%e y=%e err=%e j=%d\n",res1,res2,x,y,err,j);
00052        serr +=err;
00053      }
00054   }
00055   printf("Average Error = %e\n",serr/nmax);
00056 }
00057 
00058 void binomial () {
00059    binomialSimple();
00060    binomialFancy();
00061 }
00062 

Generated on Tue Jul 5 15:44:49 2011 for ROOT_528-00b_version by  doxygen 1.5.1