1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
|
From f34734ffb4c58d6f3ec3d177efcff24f379b41b8 Mon Sep 17 00:00:00 2001 From: Antonis Geralis <43617260+planetis-m@users.noreply.github.com> Date: Mon, 18 Jul 2022 22:18:12 +0300 Subject: Improve rand(bool) (#20045) * Improve rand(bool) * Use sign test instead of mod 2 * Use mod 2 again, as it works for js * Use right shift as suggested by the authors of xoroshiro * Update random.nim * General case doesn't need any right shift it was correct to begin with * Update random.nim * add comment Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com> --- lib/pure/random.nim | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/pure/random.nim b/lib/pure/random.nim index 832d54e3d..7676ce6cf 100644 --- a/lib/pure/random.nim +++ b/lib/pure/random.nim @@ -377,10 +377,12 @@ proc rand*[T: Ordinal](t: typedesc[T]): T = assert rand(range[1..16]) in 1..16 # pending csources >= 1.4.0 or fixing https://github.com/timotheecour/Nim/issues/251#issuecomment-831599772, # use `runnableExamples("-r:off")` instead of `if false` - when T is range or T is enum or T is bool: + when T is range or T is enum: result = rand(state, low(T)..high(T)) + elif T is bool: + result = state.next shr 63 == 1 # sign test, works on js else: - result = cast[T](state.next) + result = cast[T](state.next shr (64 - sizeof(T)*8)) proc sample*[T](r: var Rand; s: set[T]): T = ## Returns a random element from the set `s` using the given state. -- cgit 1.4.1-2-gfad0 051scenario_test.mu?h=hlt'>log tree commit diff stats