ROOT  6.07/01
Reference Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
binomial.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_math
3 /// tutorial illustrating the use of TMath::Binomial
4 /// can be run with:
5 ///
6 /// ~~~ {.cpp}
7 /// root > .x binomial.C
8 /// root > .x binomial.C+ with ACLIC
9 /// ~~~
10 ///
11 /// \macro_output
12 /// \macro_code
13 ///
14 /// \author Federico Carminati
15 
16 #include <TMath.h>
17 #include <TRandom.h>
18 
19 void binomialSimple() {
20  //
21  // Simple test for the binomial distribution
22  //
23  printf("\nTMath::Binomial simple test\n");
24  printf("Build the Tartaglia triangle\n");
25  printf("============================\n");
26  const Int_t max=13;
27  Int_t j;
28  for(Int_t i=0;i<max;i++) {
29  printf("n=%2d",i);
30  for(j=0;j<(max-i);j++) printf(" ");
31  for(j=0;j<i+1;j++) printf("%4d",TMath::Nint(TMath::Binomial(i,j)));
32  printf("\n");
33  }
34 }
35 
36 void binomialFancy() {
37  Double_t x;
38  Double_t y;
39  Double_t res1;
40  Double_t res2;
41  Double_t err;
42  Double_t serr=0;
43  const Int_t nmax=10000;
44  printf("\nTMath::Binomial fancy test\n");
45  printf("Verify Newton formula for (x+y)^n\n");
46  printf("x,y in [-2,2] and n from 0 to 9 \n");
47  printf("=================================\n");
48  TRandom r;
49  for(Int_t i=0; i<nmax; i++) {
50  do {
51  x=2*(1-2*r.Rndm());
52  y=2*(1-2*r.Rndm());
53  } while (TMath::Abs(x+y)<0.75); //Avoid large cancellations
54  for(Int_t j=0; j<10; j++) {
55  res1=TMath::Power(x+y,j);
56  res2=0;
57  for(Int_t k=0; k<=j; k++)
58  res2+=TMath::Power(x,k)*TMath::Power(y,j-k)*TMath::Binomial(j,k);
59  if((err=TMath::Abs(res1-res2)/TMath::Abs(res1))>1e-10)
60  printf("res1=%e res2=%e x=%e y=%e err=%e j=%d\n",res1,res2,x,y,err,j);
61  serr +=err;
62  }
63  }
64  printf("Average Error = %e\n",serr/nmax);
65 }
66 
67 void binomial () {
68  binomialSimple();
69  binomialFancy();
70 }
71 
virtual Double_t Rndm(Int_t i=0)
Machine independent random number generator.
Definition: TRandom.cxx:512
int Int_t
Definition: RtypesCore.h:41
Short_t Abs(Short_t d)
Definition: TMathBase.h:110
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Definition: TMath.h:501
Double_t x[n]
Definition: legend1.C:17
This is the base class for the ROOT Random number generators.
Definition: TRandom.h:29
ROOT::R::TRInterface & r
Definition: Object.C:4
Double_t Binomial(Int_t n, Int_t k)
Calculate the binomial coefficient n over k.
Definition: TMath.cxx:2072
double Double_t
Definition: RtypesCore.h:55
ClassImp(TMCParticle) void TMCParticle printf(": p=(%7.3f,%7.3f,%9.3f) ;", fPx, fPy, fPz)
Double_t y[n]
Definition: legend1.C:17
static Vc_ALWAYS_INLINE int_v max(const int_v &x, const int_v &y)
Definition: vector.h:440
Int_t Nint(T x)
Definition: TMath.h:480