Main Menu

random floats

Started by Alex777, February 01, 2006, 04:05:21 PM

Previous topic - Next topic

Alex777

Some quick testing of Rnd# and RndRange# suggests, to me anyway, that they can return a uniform distribution of random integers PROVIDED THAT:

  - with RndRange#: you add 1 to the top end of the range and then round down;

  - with Rnd#: you round up

Here is some code which generates 1,000,000 random integers with each function, and displays the distribution graphically:

PlayBASIC Code: [Select]
OpenScreen 1024, 768, 16, 2
RenderToScreen
Cls RGB(255, 255, 255)

Randomize Timer()

Dim result(1000, 1)

For n = 1 To 1000000
x = RoundDown(RndRange#(1, 1001))
y = RoundUp(Rnd#(1) * 1000)
result(x, 0) = result(x, 0) + 1
result(y, 1) = result(y, 1) + 1
Next n

LineC 0, 700, 1000, 700, RGB(255, 0, 0)

For n = 1 To 1000
; scale the result to fit on the screen
CircleC n, 700 - (result(n, 0) / 3), 2, 1, RGB(8, 8, 8)
CircleC n, 700 - (result(n, 1) / 3), 2, 1, RGB(255, 0, 0)
Next n

Ink RGB(8, 8, 8)
LoadFont "Courier", 1, 18, 0
SetFont 1
Text 100, 100, "RndRange# returned " + Str$(result(1, 0)) + " random numbers = 1"
Text 100, 130, "RndRange# returned " + Str$(result(1000, 0)) + " random numbers = 1000"
Ink RGB(255, 0, 0)
Text 100, 160, "Rnd# returned " + Str$(result(1, 1)) + " random numbers = 1"
Text 100, 190, "Rnd# returned " + Str$(result(1000, 1)) + " random numbers = 1000"

Sync
WaitKey






EDIT: This is not entirely accurate, we recommend reading the Variable Casting and Math operations FAQ