Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to expand a [0,1] interval to [a,b]?

Many random-number generators return floating numbers between 0 and 1.

What's the best and correct way to get integers between a and b?

like image 686
Georg Schölly Avatar asked Jan 22 '23 22:01

Georg Schölly


2 Answers

Divide the interval [0,1] in B-A+1 bins

Example A=2, B=5

        [----+----+----+----]
        0    1/4  1/2  3/4  1
Maps to    2    3    4    5

The problem with the formula

 Int (Rnd() * (B-A+1)) + A

is that your Rnd() generation interval is closed on both sides, thus the 0 and the 1 are both possible outputs and the formula gives 6 when the Rnd() is exactly 1.

In a real random distribution (not pseudo), the 1 has probability zero. I think it is safe enough to program something like:

 r=Rnd()
 if r equal 1
     MyInt = B
 else
     MyInt = Int(r * (B-A+1)) + A
 endif

Edit

Just a quick test in Mathematica:

Define our function:

f[a_, b_] :=  If[(r = RandomReal[]) == 1, b, IntegerPart[r (b - a + 1)] + a]

Build a table with 3 10^5 numbers in [1,100]:

table = SortBy[Tally[Table[f[1, 100], {300000}]], First]

Check minimum and maximum:

In[137]:= {Max[First /@ table], Min[First /@ table]}

Out[137]= {100, 1}  

Lets see the distribution:

BarChart[Last /@ SortBy[Tally[Table[f[1, 100], {300000}]], First],
        ChartStyle -> "DarkRainbow"]  

alt text

like image 64
Dr. belisarius Avatar answered Jan 24 '23 11:01

Dr. belisarius


X = (Rand() * (B - A)) + A
like image 44
nothrow Avatar answered Jan 24 '23 10:01

nothrow