Menu

#849 'Randomize , 5' produces a poor distribution of numbers

closed
nobody
RND (2)
rtlib
2020-11-09
2017-02-23
Matthew
No

I tried the following code, which counts the number of iterations of Rnd before exactly 0 is reached.

for i as integer = 1 to 10
    randomize , 5

    dim as integer count = 0
    do
        count += 1
    loop until rnd() = 0
    print count

next i

And I got results like this:
68273218
177110524
31156482
24495696
38494895
20011479
15631759
28712887
119226508
116418089

The highest number of iterations here was 177 million, when you would tend expect around 4 billion for 2^32 possiblities.

I explain the main reason why here: http://freebasic.net/forum/viewtopic.php?f=7&t=25407&p=229425#p229398
It's because of the line that multiplies v by mtwist, which has a similar effect to multipying together two 32-bit numbers and taking the high 32 bits - you would not expect those numbers to evenly cover the range of possibilities.
Because 0 is most likely, and the number 0 is also left unaffected by the transformations that follow, then 0.0 (exactly) is a likely output.

I think the algorithm involved should be rewritten in a different way, although it will be challenging to produce sequences that are evenly distributed and unpredictable.

Discussion

  • Jeff Marshall

    Jeff Marshall - 2020-11-09
    • labels: --> RND
    • status: open --> closed
     
  • Jeff Marshall

    Jeff Marshall - 2020-11-09

    changed in fbc-1.08.0 [ffbca5345a7e89d7297a978e54d9fce5011f92bc] which was part of several other changes to the built-in random number generators.

    The FB_RND_REAL (5) generator now uses a buffer to store values from the system call. FB_RND_MTWIST (3) is only used as a fall back if the system calls are not available.

    Extended discussion on PRNGs also at Threadsafe RANDOMIZE and RND

     

    Related

    Commit: [ffbca5]


    Last edit: Jeff Marshall 2020-11-09

Log in to post a comment.