From 294989daf515d8cad63bb30a8a80e39a45766a80 Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 11 Jun 2015 18:47:28 -0400 Subject: Updated random functions For Windows, `rand_s` has been available since Windows XP (see https://msdn.microsoft.com/en-us/library/sxtz2fa8.aspx). It gives a better quality random number in a larger range (the max is actually `0xffffffff`). --- lib/pure/math.nim | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'lib/pure') diff --git a/lib/pure/math.nim b/lib/pure/math.nim index a9e9010f6..6c03dee4f 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -202,8 +202,15 @@ when not defined(JS): ## computes x to power raised of y. # C procs: - proc srand(seed: cint) {.importc: "srand", header: "".} - proc rand(): cint {.importc: "rand", header: "".} + when defined(windows): + # The "secure" random, available from Windows XP + # https://msdn.microsoft.com/en-us/library/sxtz2fa8.aspx + proc rand_s(val: var cuint) {.importc: "rand_s", header: "".} + # To behave like the normal version + proc rand(): cuint = rand_s(result) + else: + proc srand(seed: cint) {.importc: "srand", header: "".} + proc rand(): cint {.importc: "rand", header: "".} when not defined(windows): proc srand48(seed: clong) {.importc: "srand48", header: "".} @@ -216,13 +223,14 @@ when not defined(JS): # importcing macros is extremely problematic # and because the value is publicly documented # on MSDN and very unlikely to change - const rand_max = 32767 + # See https://msdn.microsoft.com/en-us/library/296az74e.aspx + const rand_max = 4294967295 result = (float(rand()) / float(rand_max)) * max proc randomize() = randomize(cast[int](epochTime())) proc randomize(seed: int) = - srand(cint(seed)) + when declared(srand): srand(cint(seed)) # rand_s doesn't use srand when declared(srand48): srand48(seed) proc random(max: int): int = result = int(rand()) mod max -- cgit 1.4.1-2-gfad0 n>
blob: c165ffa3d2ddc753a00fc042bbaaef1a630395c9 (plain) (tree)
1
2
3
4
5
6
7
8
9