Gentoo Archives: gentoo-user

From: null_ptr <rhannek@×××.de>
To: gentoo-user@l.g.o
Subject: Re: [gentoo-user] OT: Mapping random numbers (PRNG)
Date: Fri, 06 Jun 2014 19:38:17
Message-Id: 20140606193752.GA17757@gmx.de
In Reply to: Re: [gentoo-user] OT: Mapping random numbers (PRNG) by meino.cramer@gmx.de
1 On 06/06/14 20:39, meino.cramer@×××.de wrote:
2 >To get an better imagination of that...suppose the rand() would only
3 >return numbers in the range of 1...12 and the alphabet has only 8
4 >characters (as 2^32 is not devideable by 62)
5 >
6 >rand():
7 >1 2 3 4 5 6 7 8 9 10 11 12
8 >
9 >rand()%N : rand()%7
10 >1 2 3 4 5 6 7 0 1 2 3 4
11 >
12 >or in other words: An even distribution of numbers of rand()
13 >would result in a unevenly distributed sequence of characters...or?
14 >This would break the quality of ISAACs output.
15 >
16 >I am sure I did something wrong here...but where is the logic trap?
17
18 You thought on that is totally right.
19 Let's say random numbers have the rande [0..RAND_MAX]
20 Blindly calculating modulus
21 creates a bias towards lower numbers if RAND_MAX+1 is not divisible
22 by N. For most applications this bias is negligible. If you really
23 want the same distribution you have to discard numbers greater than
24 RAND_MAX - ((RAND_MAX+1)%N)
25 (Beware the undefined behaviour in the above line if you try C.)
26 Basically you want one less than the largest by N dividable number
27 in your range.
28
29 With numbers:
30 rand():
31 0 1 2 3 4 5 6 7 8 9 10 11 12
32 rand()%5 with discarding >12-((12+1)%5)=9:
33 0 1 2 3 4 0 1 2 3 4 discarded
34
35 ---
36 null_ptr
37 Please don't follow me.