fixes #22360; compare with the half of randMax (#22361)

* fixes #22360; compare with the half of randMax

* add a test

(cherry picked from commit f3a7622514)
This commit is contained in:
ringabout
2023-08-02 16:58:29 +08:00
committed by narimiran
parent 3ad16028aa
commit 413395866f
2 changed files with 19 additions and 4 deletions

View File

@@ -381,10 +381,7 @@ proc rand*[T: Ordinal](r: var Rand; t: typedesc[T]): T {.since: (1, 7, 1).} =
when T is range or T is enum:
result = rand(r, low(T)..high(T))
elif T is bool:
whenJsNoBigInt64:
result = (r.next or 0) < 0
do:
result = cast[int64](r.next) < 0
result = r.next < randMax div 2
else:
whenJsNoBigInt64:
result = cast[T](r.next shr (sizeof(uint)*8 - sizeof(T)*8))

View File

@@ -282,3 +282,21 @@ block: # bug #17898
for j in 0..<numRepeat:
discard rands[i].next
doAssert rands[i] notin randSet
block: # bug #22360
const size = 1000
var fc = 0
var tc = 0
for _ in 1..size:
let s = rand(bool)
if s:
inc tc
else:
inc fc
when defined(js):
doAssert (tc, fc) == (483, 517), $(tc, fc)
else:
doAssert (tc, fc) == (510, 490), $(tc, fc)