Debian Codegraph @

rpython/rlib/test/test_rrandom.py

raw symbols SCIP
1 import _random
2
3 from rpython.rlib.rarithmetic import intmask
4 from rpython.rlib.rrandom import Random, N, r_uint
5 from rpython.translator.c.test.test_genc import compile
6
7 # the numbers were created by using CPython's _randommodule.c
8
9 def test_init_from_zero():
10 rnd = Random(0)
11 assert rnd.state[:14] == [0, 1, 1812433255, 1900727105, 1208447044,
12 2481403966, 4042607538, 337614300, 3232553940,
13 1018809052, 3202401494, 1775180719, 3192392114, 594215549]
14
15 def test_init_from_seed():
16 rnd = Random(1000)
17 assert rnd.state[:14] == [1000, 4252021385, 1724402292, 571538732,
18 73690720, 4283493349, 2222270404, 2464917285, 427676011,
19 1101193792, 2887716015, 3670250828, 1664757559, 1538426459]
20
21 def test_numbers():
22 rnd = Random(1000)
23 nums = [rnd.genrand32() for i in range(14)]
24 assert nums == [2807145907, 882709079, 493951047, 2621574848, 4081433851,
25 44058974, 2070996316, 1549632257, 3747249597, 3650674304,
26 911961945, 58396205, 174846504, 1478498153]
27
28 def test_init_by_array():
29 rnd = Random()
30 rnd.init_by_array([r_uint(n) for n in [1, 2, 3, 4]])
31 assert rnd.state[:14] == [2147483648, 1269538435, 699006892, 381364451,
32 172015551, 3237099449, 3609464087, 2187366456, 654585064,
33 2665903765, 3735624613, 1241943673, 2038528247, 3774211972]
34 # try arrays of various sizes to test for corner cases
35 for size in [N, N - 1, N + 1, N // 2, 2 * N]:
36 rnd.init_by_array([r_uint(n) for n in range(N)])
37
38 def test_jumpahead():
39 rnd = Random()
40 rnd.state = [r_uint(0)] * N
41 rnd.state[0] = r_uint(1)
42 cpyrandom = _random.Random()
43 cpyrandom.setstate(tuple([int(s) for s in rnd.state] + [rnd.index]))
44 rnd.jumpahead(100)
45 cpyrandom.jumpahead(100)
46 assert tuple(rnd.state) + (rnd.index, ) == cpyrandom.getstate()
47
48
49 def test_jumpahead_badstate():
50 rnd = Random()
51 s, j = 4043161618, 2674112291824205302
52 rnd.init_by_array([s])
53 rnd.jumpahead(j)
54 for i in range(500):
55 r = rnd.random()
56 assert r <= 1.0, (r, i)
57
58 def test_translate():
59 def f(x, y):
60 x = r_uint(x)
61 y = r_uint(y)
62 rnd = Random(x)
63 rnd.init_by_array([x, y])
64 rnd.jumpahead(intmask(y))
65 return float(rnd.genrand32()) + rnd.random()
66 fc = compile(f, [int, int])
67 assert fc(1, 2) == f(1, 2)