Logo ROOT  
Reference Guide
binomial.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_math
3/// \notebook -nodraw
4/// tutorial illustrating the use of TMath::Binomial
5/// can be run with:
6///
7/// ~~~{.cpp}
8/// root > .x binomial.C
9/// root > .x binomial.C+ with ACLIC
10/// ~~~
11///
12/// \macro_output
13/// \macro_code
14///
15/// \author Federico Carminati
16
17#include <TMath.h>
18#include <TRandom.h>
19
20void binomialSimple() {
21 //
22 // Simple test for the binomial distribution
23 //
24 printf("\nTMath::Binomial simple test\n");
25 printf("Build the Tartaglia triangle\n");
26 printf("============================\n");
27 const Int_t max=13;
28 Int_t j;
29 for(Int_t i=0;i<max;i++) {
30 printf("n=%2d",i);
31 for(j=0;j<(max-i);j++) printf(" ");
32 for(j=0;j<i+1;j++) printf("%4d",TMath::Nint(TMath::Binomial(i,j)));
33 printf("\n");
34 }
35}
36
37void binomialFancy() {
38 Double_t x;
39 Double_t y;
40 Double_t res1;
41 Double_t res2;
42 Double_t err;
43 Double_t serr=0;
44 const Int_t nmax=10000;
45 printf("\nTMath::Binomial fancy test\n");
46 printf("Verify Newton formula for (x+y)^n\n");
47 printf("x,y in [-2,2] and n from 0 to 9 \n");
48 printf("=================================\n");
49 TRandom r;
50 for(Int_t i=0; i<nmax; i++) {
51 do {
52 x=2*(1-2*r.Rndm());
53 y=2*(1-2*r.Rndm());
54 } while (TMath::Abs(x+y)<0.75); //Avoid large cancellations
55 for(Int_t j=0; j<10; j++) {
56 res1=TMath::Power(x+y,j);
57 res2=0;
58 for(Int_t k=0; k<=j; k++)
59 res2+=TMath::Power(x,k)*TMath::Power(y,j-k)*TMath::Binomial(j,k);
60 if((err=TMath::Abs(res1-res2)/TMath::Abs(res1))>1e-10)
61 printf("res1=%e res2=%e x=%e y=%e err=%e j=%d\n",res1,res2,x,y,err,j);
62 serr +=err;
63 }
64 }
65 printf("Average Error = %e\n",serr/nmax);
66}
67
68void binomial () {
69 binomialSimple();
70 binomialFancy();
71}
72
ROOT::R::TRInterface & r
Definition: Object.C:4
#define e(i)
Definition: RSha256.hxx:103
int Int_t
Definition: RtypesCore.h:43
double Double_t
Definition: RtypesCore.h:57
This is the base class for the ROOT Random number generators.
Definition: TRandom.h:27
Double_t y[n]
Definition: legend1.C:17
Double_t x[n]
Definition: legend1.C:17
Int_t Nint(T x)
Round to nearest integer. Rounds half integers to the nearest even integer.
Definition: TMath.h:703
Double_t Binomial(Int_t n, Int_t k)
Calculate the binomial coefficient n over k.
Definition: TMath.cxx:2083
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Definition: TMath.h:725
Short_t Abs(Short_t d)
Definition: TMathBase.h:120