Skip to content

Commit a04ffb8

Browse files
committed
Check uinteger and normalize has_uint32 in the PCG64DXSM state setter
1 parent 20ff9e9 commit a04ffb8

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

‎dpnp/random/_bit_generator.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -644,8 +644,13 @@ def state(self, value):
644644

645645
state = int(value["state"]["state"]) & _MASK128
646646
inc = int(value["state"]["inc"]) & _MASK128
647-
has_uint32 = int(value["has_uint32"])
648-
uinteger = int(value["uinteger"]) & 0xFFFFFFFF
647+
# NumPy takes any has_uint32 and tests it against 0
648+
has_uint32 = int(int(value["has_uint32"]) != 0)
649+
uinteger = int(value["uinteger"])
650+
if uinteger < 0:
651+
raise OverflowError("can't convert negative value to uint32_t")
652+
if uinteger > 0xFFFFFFFF:
653+
raise OverflowError("value too large to convert to uint32_t")
649654
with self._lock:
650655
self._set_state(state, inc, has_uint32, uinteger)
651656

‎dpnp/tests/test_random_generator.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,26 @@ def test_state_errors(self):
571571
ValueError, setattr, bg, "state", {"bit_generator": "PCG64"}
572572
)
573573

574+
ref = numpy.random.PCG64DXSM(42)
575+
for uinteger in [-1, 2**32]:
576+
state = dict(ref.state, uinteger=uinteger)
577+
_assert_same_error(
578+
lambda: setattr(ref, "state", state),
579+
lambda: setattr(bg, "state", state),
580+
)
581+
582+
def test_state_has_uint32(self):
583+
# NumPy takes any nonzero has_uint32 as true
584+
ref = numpy.random.PCG64DXSM(43)
585+
state = dict(ref.state, has_uint32=-1, uinteger=12345)
586+
ref.state = state
587+
bg = PCG64DXSM()
588+
bg.state = state
589+
assert bg.state["has_uint32"] == 1
590+
res = Generator(bg).random(3, dtype=dpnp.float32)
591+
exp = numpy.random.Generator(ref).random(3, dtype=numpy.float32)
592+
assert_array_equal(res, exp)
593+
574594
def test_spawn(self):
575595
children = PCG64DXSM(5).spawn(2)
576596
ref = numpy.random.PCG64DXSM(5).spawn(2)

0 commit comments

Comments
 (0)