Re: How to generate random 32bit integers
- Posted by DerekParnell (admin) Feb 18, 2011
- 1720 views
DerekParnell said...
Ok then, try ...
Actually, do not try that last one of mine. I just quickly wrote that during my lunch break. Now that I'm home and thought it through, it has holes. Sorry.
Anyhow, here are two different ways that you can try...
-- This first function is used locally and is not suitable for your purposes. function r32() -- return a random number from 1 to power(2,32) return ((rand(#10000) - 1) * #10000) + rand(#10000) end function -- Method A: Calculate two random numbers and join them. global function rand_A(atom N) integer A integer B if N <= #3FFFFFFF then return rand(N) end if A = floor(N / #10000) B = rand(A + 1) - 1 if B != A then A = rand(#FFFF) else A = remainder(N, #10000) if A then A = rand(A) end if end if return ((B * #10000) + A) -- Returns an ATOM not an INTEGER, in the range 1 to N end function -- Method B: Calculate a random number such that 0 < R <= 1, then multiple that by N global function rand_B(atom N) atom a,b,temp atom A, B atom UL,LL if N <= #3FFFFFFF then return rand(N) end if UL = (N - 1.5) / N LL = 1.5 / N a = r32() / r32() b = r32() / r32() if a > b then temp = b b = a a = temp end if A = a / b if A > UL then return N elsif A < LL then return 1 end if B = floor(N * A) return B end function --------------------
The distributions are different in the two methods so your sampling might be better with one method rather than the other. You'll have to test which is more suitable.