Skip to content

Commit

Permalink
fixes #23915; std/random produces different results on c/js
Browse files Browse the repository at this point in the history
  • Loading branch information
ringabout committed Aug 22, 2024
1 parent cb7bcae commit af693e4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
11 changes: 7 additions & 4 deletions lib/pure/random.nim
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ when defined(nimPreviewSlimSystem):
include system/inclrtl
{.push debugger: off.}

when defined(js):
when defined(js) and not compileOption("jsbigint64"):
type Ui = uint32

const randMax = 4_294_967_295u32
Expand All @@ -105,7 +105,7 @@ type
## generator are **not** thread-safe!
a0, a1: Ui

when defined(js):
when defined(js) and not compileOption("jsbigint64"):
var state = Rand(
a0: 0x69B4C98Cu32,
a1: 0xFED1DD30u32) # global for backwards compatibility
Expand Down Expand Up @@ -208,7 +208,7 @@ proc skipRandomNumbers*(s: var Rand) =
doAssert vals == [501737, 497901, 500683, 500157]


when defined(js):
when defined(js) and not compileOption("jsbigint64"):
const helper = [0xbeac0467u32, 0xd86b048bu32]
else:
const helper = [0xbeac0467eba5facbu64, 0xd86b048b86aa9922u64]
Expand Down Expand Up @@ -294,7 +294,10 @@ proc rand*(r: var Rand; max: range[0.0 .. high(float)]): float {.benign.} =

let x = next(r)
when defined(js):
result = (float(x) / float(high(uint32))) * max
when compileOption("jsbigint64"):
result = (float(x) / float(high(uint64))) * max
else:
result = (float(x) / float(high(uint32))) * max
else:
let u = (0x3FFu64 shl 52u64) or (x shr 12u64)
result = (cast[float](u) - 1.0) * max
Expand Down
15 changes: 10 additions & 5 deletions tests/stdlib/trandom.nim
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ block:
type DiceRoll = range[0..6]
when not defined(js):
doAssert rand(DiceRoll).int == 3
elif compileOption("jsbigint64"):
doAssert rand(DiceRoll).int == 1
else:
doAssert rand(DiceRoll).int == 6

Expand Down Expand Up @@ -296,10 +298,13 @@ block: # bug #22360
else:
inc fc

when defined(js):
when compileOption("jsbigint64"):
doAssert (tc, fc) == (517, 483), $(tc, fc)
else:
doAssert (tc, fc) == (515, 485), $(tc, fc)
when defined(js) and not compileOption("jsbigint64"):
doAssert (tc, fc) == (515, 485), $(tc, fc)
else:
doAssert (tc, fc) == (510, 490), $(tc, fc)

block:
when defined(js) and not compileOption("jsbigint64"):
doAssert rand(int32.high) == 335507522
else:
doAssert rand(int32.high) == 607539621

0 comments on commit af693e4

Please sign in to comment.