[pypy-commit] pypy numpy-random: implement a few numpy.random methods

timo_jbo noreply at buildbot.pypy.org
Sat Sep 24 20:31:23 CEST 2011


Author: Timo Paulssen <timonator at perpetuum-immobile.de>
Branch: numpy-random
Changeset: r47585:3ae0ae8e9c00
Date: 2011-09-24 20:28 +0200
http://bitbucket.org/pypy/pypy/changeset/3ae0ae8e9c00/

Log:	implement a few numpy.random methods

diff --git a/lib_pypy/numpy/random.py b/lib_pypy/numpy/random.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/numpy/random.py
@@ -0,0 +1,31 @@
+from __future__ import absolute_import
+
+from numpy import array
+import random
+
+_random = random.Random()
+
+def get_state():
+    return _random.getstate()
+
+def set_state(state):
+    _random.setstate(state)
+
+def seed(seed):
+    _random.seed(seed)
+
+def rand(*shape):
+    assert len(shape) == 1
+
+    return array(_random.random() for x in range(shape[0]))
+
+def randn(*shape):
+    if len(shape) == 0:
+        return _random.gauss(0, 1)
+    assert len(shape) == 1
+
+    return array(_random.gauss(0, 1) for x in range(shape[0]))
+
+def standard_normal(size=None):
+    return randn(*size)
+
diff --git a/lib_pypy/pypy_test/test_numpy_random.py b/lib_pypy/pypy_test/test_numpy_random.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/pypy_test/test_numpy_random.py
@@ -0,0 +1,63 @@
+from pypy.conftest import gettestobjspace
+
+class AppTestRandom:
+    def setup_class(cls):
+        cls.space = gettestobjspace(usemodules=['_numpy'])
+
+    def test_rand_single(self):
+        from numpy.random import rand
+        from numpy import array, dtype
+
+        single = rand(1)
+        assert isinstance(single, array)
+        assert single.dtype is dtype(float)
+        assert single.shape == (1,)
+        assert single[0] >= 0
+        assert single[0] < 1
+
+    def test_rand_multiple(self):
+        from numpy.random import rand
+        from numpy import dtype
+
+        multi = rand(5)
+
+        assert multi.shape == (5,)
+        assert min(multi) >= 0
+        assert max(multi) < 1
+        assert multi.dtype is dtype(float)
+
+    def test_randn_single(self):
+        from numpy.random import randn
+
+        single = randn()
+
+        assert isinstance(single, float)
+
+    def test_randn_multiple(self):
+        from numpy.random import randn
+
+        multi = randn(6)
+
+        assert multi.shape == (6,)
+
+    def test_state(self):
+        from numpy.random import set_state, get_state, randn
+
+        state = get_state()
+        number = randn()
+        other_number = randn()
+
+        set_state(state)
+        assert randn() == number
+        assert randn() == other_number
+
+    def test_seed(self):
+        from numpy.random import seed, rand
+
+        seed(9001)
+        number = rand(1)[0]
+        other_number = rand(1)[0]
+
+        seed(9001)
+        assert number == rand(1)[0]
+        assert other_number == rand(1)[0]


More information about the pypy-commit mailing list