Re: rand() and RAND_MAX won't match

From: Christian Holm Christensen <cholm_at_nbi.dk>
Date: Mon, 13 Nov 2006 16:37:53 +0100


Hi,

On Sun, 2006-11-12 at 21:23 -0500, 秋叶原 wrote:
> Hi,
>
> I am using root to run my little cpp code.
> RAND_MAX is defined as (long)2147483647.
> But rand() generates only 5-digit number which is much smaller than
> RAND_MAX.
> Am i missing something here? How to use rand() and RAND_MAX to make my
> code run properly?

Try running the code

        void
        random()
        {
           TH1* h = new TH1F("h", "h", 100, 0, 1);
           for (size_t i = 0; i < 100000; i++) {
              double x = double(rand()) / RAND_MAX;
              h->Fill(x);
          }
          h->SetMinimum(0);
          h->Draw();
        }
        
        

It should give you a more or less flat distribution in [0,1).

Better than using rand() is to use TRandom.

Yours,

-- 
 ___  |  Christian Holm Christensen 
  |_| |  -------------------------------------------------------------
    | |  Address: Sankt Hansgade 23, 1. th.  Phone:  (+45) 35 35 96 91
     _|           DK-2200 Copenhagen N       Cell:   (+45) 24 61 85 91
    _|            Denmark                    Office: (+45) 353  25 404
 ____|   Email:   cholm_at_nbi.dk               Web:    www.nbi.dk/~cholm
 | |
Received on Mon Nov 13 2006 - 16:38:11 MET

This archive was generated by hypermail 2.2.0 : Mon Jan 01 2007 - 16:32:01 MET