def test_numbers(): rnd = Random(1000) nums = [rnd.genrand32() for i in range(14)] assert nums == [ 2807145907, 882709079, 493951047, 2621574848, 4081433851, 44058974, 2070996316, 1549632257, 3747249597, 3650674304, 911961945, 58396205, 174846504, 1478498153 ]
def test_init_by_array(): rnd = Random() rnd.init_by_array([r_uint(n) for n in [1, 2, 3, 4]]) assert rnd.state[:14] == [2147483648, 1269538435, 699006892, 381364451, 172015551, 3237099449, 3609464087, 2187366456, 654585064, 2665903765, 3735624613, 1241943673, 2038528247, 3774211972] # try arrays of various sizes to test for corner cases for size in [N, N - 1, N + 1, N // 2, 2 * N]: rnd.init_by_array([r_uint(n) for n in range(N)])
def test_jumpahead(): rnd = Random() rnd.state = [r_uint(0)] * N rnd.state[0] = r_uint(1) cpyrandom = _random.Random() cpyrandom.setstate(tuple([int(s) for s in rnd.state] + [rnd.index])) rnd.jumpahead(100) cpyrandom.jumpahead(100) assert tuple(rnd.state) + (rnd.index, ) == cpyrandom.getstate()
class rand(object): def seed(self, seed): self.r = Random(seed) def random(self): return self.r.random() def randint(self, a, b): r32 = intmask(self.r.genrand32()) r = a + r32 % (b - a) return intmask(r)
def srand(self, space, seed=None): previous_seed = self.w_seed if seed is None: seed = intmask(self._generate_seed()) else: seed = Coerce.int(space, seed) self.w_seed = space.newint(seed) if previous_seed is None: value = space.newfloat(self.random.random()) else: value = previous_seed self.random = Random(abs(seed)) return value
def f(x, y): x = r_uint(x) y = r_uint(y) rnd = Random(x) rnd.init_by_array([x, y]) rnd.jumpahead(intmask(y)) return float(rnd.genrand32()) + rnd.random()
def test_init_from_seed(): rnd = Random(1000) assert rnd.state[:14] == [ 1000, 4252021385, 1724402292, 571538732, 73690720, 4283493349, 2222270404, 2464917285, 427676011, 1101193792, 2887716015, 3670250828, 1664757559, 1538426459 ]
class rand(object): def seed(self, seed): self.r = Random(seed) def randint(self, a, b): r32 = intmask(self.r.genrand32()) r = a + r32 % (b - a) return intmask(r)
def test_init_from_zero(): rnd = Random(0) assert rnd.state[:14] == [ 0, 1, 1812433255, 1900727105, 1208447044, 2481403966, 4042607538, 337614300, 3232553940, 1018809052, 3202401494, 1775180719, 3192392114, 594215549 ]
def __init__(self, avoid_exit = False): self._interpreter = Interpreter(self) self._symbol_table = {} self._globals = {} self.nilObject = None self.trueObject = None self.falseObject = None self.objectClass = None self.classClass = None self.metaclassClass = None self.nilClass = None self.integerClass = None self.arrayClass = None self.methodClass = None self.symbolClass = None self.primitiveClass = None self.systemClass = None self.blockClass = None self.blockClasses = None self.stringClass = None self.doubleClass = None self._last_exit_code = 0 self._avoid_exit = avoid_exit self._dump_bytecodes = False self.classpath = None self.start_time = time.time() # a float of the time in seconds self.random = Random(abs(int(time.clock() * time.time()))) CURRENT = self
def __init__(self, avoid_exit=False): self._symbol_table = {} self._globals = {} self.objectClass = None self.classClass = None self.metaclassClass = None self.nilClass = None self.integerClass = None self.arrayClass = None self.methodClass = None self.symbolClass = None self.primitiveClass = None self.systemClass = None self.blockClass = None self.blockClasses = None self.stringClass = None self.contextClass = None self.characterClass = None self.doubleClass = None self.environmentMOClass = None self.operationalSemanticsMOClass = None self.messageMOClass = None self.layoutMOClass = None self._last_exit_code = 0 self._avoid_exit = avoid_exit self._dump_bytecodes = False self.classpath = None self.start_time = time.time() # a float of the time in seconds self.random = Random(abs(int(time.clock() * time.time()))) self._object_system_initialized = False self._mate_enabled = False
def test_jumpahead_badstate(): rnd = Random() s, j = 4043161618, 2674112291824205302 rnd.init_by_array([s]) rnd.jumpahead(j) for i in range(500): r = rnd.random() assert r <= 1.0, (r, i)
class W_RandomObject(W_Object): classdef = ClassDef("Random", W_Object.classdef, filepath=__file__) def __init__(self, space, klass=None): W_Object.__init__(self, space, klass) self.random = Random() @classdef.singleton_method("allocate") def method_allocate(self, space): return W_RandomObject(space, self) @classdef.method("rand") def method_rand(self, space): return space.newfloat(self.random.random())
def test_init_by_array(): rnd = Random() rnd.init_by_array([r_uint(n) for n in [1, 2, 3, 4]]) assert rnd.state[:14] == [ 2147483648, 1269538435, 699006892, 381364451, 172015551, 3237099449, 3609464087, 2187366456, 654585064, 2665903765, 3735624613, 1241943673, 2038528247, 3774211972 ] # try arrays of various sizes to test for corner cases for size in [N, N - 1, N + 1, N // 2, 2 * N]: rnd.init_by_array([r_uint(n) for n in range(N)])
def test_numbers(): rnd = Random(1000) nums = [rnd.genrand32() for i in range(14)] assert nums == [2807145907, 882709079, 493951047, 2621574848, 4081433851, 44058974, 2070996316, 1549632257, 3747249597, 3650674304, 911961945, 58396205, 174846504, 1478498153]
from rpython.rlib.rrandom import Random except ImportError: import random as cpython_random # Shim for running in cpython class Random(object): def __init__(self, seed=0): cpython_random.seed(seed) def genrand32(self): return cpython_random.randint(0, 2**32 - 1) from time import time random = Random(int(time())) def is_hex(char): for x in char.lower(): if not x in "0123456789abcdef": return False return True def DEFAULT_INSTRUCTION(pointer): char = pointer.program.get(pointer.position) if is_hex(char): pointer.stack.append(int(char, 16)) return False, True return True, True
def __init__(self, space, seed=0, klass=None): W_Object.__init__(self, space, klass) self.w_seed = None self.random = Random(abs(seed))
class W_RandomObject(W_Object): classdef = ClassDef("Random", W_Object.classdef) def __init__(self, space, seed=0, klass=None): W_Object.__init__(self, space, klass) self.w_seed = None self.random = Random(abs(seed)) @classdef.setup_class def setup_class(cls, space, w_cls): default = space.send(w_cls, "new") space.set_const(w_cls, "DEFAULT", default) @classdef.singleton_method("allocate") def method_allocate(self, space): return W_RandomObject(space, 0, self) @classdef.method("initialize") def method_initialize(self, space, w_seed=None): self.srand(space, w_seed) @classdef.method("seed") def method_seed(self, space): return self.w_seed def srand(self, space, seed=None): previous_seed = self.w_seed if seed is None: seed = intmask(self._generate_seed()) else: seed = Coerce.int(space, seed) self.w_seed = space.newint(seed) if previous_seed is None: value = space.newfloat(self.random.random()) else: value = previous_seed self.random = Random(abs(seed)) return value @classdef.method("rand") def method_rand(self, space, w_max=None): if w_max is None: return space.newfloat(self.random.random()) elif space.is_kind_of(w_max, space.w_float): return self._rand_float(space, w_max) elif space.is_kind_of(w_max, space.getclassfor(W_RangeObject)): return self._rand_range(space, w_max) else: return self._rand_int(space, w_max) @classdef.singleton_method("rand") def method_singleton_rand(self, space, args_w): default = space.find_const(self, "DEFAULT") return space.send(default, "rand", args_w) def _rand_range(self, space, range): random = self.random.random() first = space.send(range, "first") last = space.send(range, "last") if space.is_true(space.send(range, "include?", [last])): last = space.send(last, "+", [space.newint(1)]) diff = space.send(last, "-", [first]) offset = space.send(diff, "*", [space.newfloat(random)]) choice = space.send(offset, "+", [first]) if (not space.is_kind_of(first, space.w_float) and not space.is_kind_of(last, space.w_float)): choice = space.send(choice, "to_i") return choice def _rand_float(self, space, float): random = self.random.random() max = Coerce.float(space, float) if max <= 0: raise space.error(space.w_ArgumentError, "invalid argument") return space.newfloat(random * max) def _rand_int(self, space, integer): random = self.random.random() max = Coerce.int(space, integer) if max <= 0: raise space.error(space.w_ArgumentError, "invalid argument") else: return space.newint(int(random * max)) def _generate_seed(self): seed = 0 if os.access('/dev/urandom', os.R_OK): file = os.open('/dev/urandom', os.R_OK, 0644) bytes = os.read(file, 4) os.close(file) for b in bytes: seed = seed * 0xff + ord(b) return seed + int(time.time()) + os.getpid()
def __init__(self, space, klass=None): W_Object.__init__(self, space, klass) self.random = Random()
class W_RandomObject(W_Object): classdef = ClassDef("Random", W_Object.classdef, filepath=__file__) def __init__(self, space, seed=0, klass=None): W_Object.__init__(self, space, klass) self.w_seed = None self.random = Random(abs(seed)) @classdef.setup_class def setup_class(cls, space, w_cls): default = space.send(w_cls, "new") space.set_const(w_cls, "DEFAULT", default) @classdef.singleton_method("allocate", seed="int") def method_allocate(self, space, seed=0): return W_RandomObject(space, seed, self) @classdef.method("initialize") def method_initialize(self, space, w_seed=None): self.srand(space, w_seed) @classdef.method("seed") def method_seed(self, space): return self.w_seed def srand(self, space, seed=None): previous_seed = self.w_seed if seed is None: seed = intmask(self._generate_seed()) else: seed = Coerce.int(space, seed) self.w_seed = space.newint(seed) if previous_seed is None: value = space.newfloat(self.random.random()) else: value = previous_seed self.random = Random(abs(seed)) return value @classdef.method("rand") def method_rand(self, space, w_max=None): if w_max is None: return space.newfloat(self.random.random()) elif space.is_kind_of(w_max, space.w_float): return self._rand_float(space, w_max) elif space.is_kind_of(w_max, space.getclassfor(W_RangeObject)): return self._rand_range(space, w_max) else: return self._rand_int(space, w_max) @classdef.singleton_method("rand") def method_singleton_rand(self, space, args_w): default = space.find_const(self, "DEFAULT") return space.send(default, "rand", args_w) def _rand_range(self, space, range): random = self.random.random() first = space.send(range, "first") last = space.send(range, "last") if space.is_true(space.send(range, "include?", [last])): last = space.send(last, "+", [space.newint(1)]) diff = space.send(last, "-", [first]) offset = space.send(diff, "*", [space.newfloat(random)]) choice = space.send(offset, "+", [first]) if (not space.is_kind_of(first, space.w_float) and not space.is_kind_of(last, space.w_float)): choice = space.send(choice, "to_i") return choice def _rand_float(self, space, float): random = self.random.random() max = Coerce.float(space, float) if max <= 0: raise space.error(space.w_ArgumentError, "invalid argument") return space.newfloat(random * max) def _rand_int(self, space, integer): random = self.random.random() max = Coerce.int(space, integer) if max <= 0: raise space.error(space.w_ArgumentError, "invalid argument") else: return space.newint(int(random * max)) def _generate_seed(self): seed = 0 if os.access('/dev/urandom', os.R_OK): file = os.open('/dev/urandom', os.R_OK, 0644) bytes = os.read(file, 4) os.close(file) for b in bytes: seed = seed * 0xff + ord(b) return seed + int(time.time()) + os.getpid()
def rrandom_example(): rnd1 = Random() print rnd1.genrand32() # get a 32-bit random number print rnd1.random() # get a float random number x, 0.0 <= x < 1.0 seed = 1546979228 rnd2 = Random(seed) # set a seed print rnd2.random() print rnd1.state # you can access the internal state of the generator # change the internal state to one different from and likely far away from # the current state, n is a non-negative integer which is used to scramble # the current state vector. n = 10 rnd1.jumpahead(n) rnd1.random()
import sys import os from rpython.rlib import rfloat, jit from rpython.rlib.rarithmetic import r_uint, intmask, ovfcheck from rpython.rlib.rstring import StringBuilder from rpython.rlib.objectmodel import we_are_translated from hippy.objects.base import W_Root from hippy.objects.boolobject import W_BoolObject from hippy.objects.intobject import W_IntObject from hippy.objects.floatobject import W_FloatObject from hippy.builtin import wrap, Optional, LongArg from rpython.rlib.rrandom import Random seed = int(os.urandom(4).encode('hex'), 16) _random = Random(seed=seed) RANDMAX = 0x7fffffff MAX_BITS = sys.maxint.bit_length() # == 31 or 63 @wrap(['space', W_Root], name="abs") def _abs(space, w_obj): return w_obj.abs(space) @wrap(['space', float]) def acos(space, d): """ acos - Arc cosine """ try: return space.wrap(math.acos(d))
def seed(self, seed): self.r = Random(seed)
class W_RandomObject(W_Object): classdef = ClassDef("Random", W_Object.classdef, filepath=__file__) def __init__(self, space, seed=0, klass=None): W_Object.__init__(self, space, klass) self.random = Random(abs(seed)) @classdef.setup_class def setup_class(cls, space, w_cls): default = space.send(w_cls, space.newsymbol("new")) space.set_const(w_cls, "DEFAULT", default) @classdef.singleton_method("allocate", seed="int") def method_allocate(self, space, seed=0): return W_RandomObject(space, seed, self) @classdef.method("initialize") def method_initialize(self, space, w_seed=None): pass @classdef.method("srand") def method_srand(self, space, args_w): self.random = Random() @classdef.singleton_method("srand") def method_singleton_srand(self, space, args_w): default = space.find_const(self, "DEFAULT") return space.send(default, space.newsymbol("srand"), args_w) @classdef.method("rand") def method_rand(self, space, w_max=None): if w_max is None: return space.newfloat(self.random.random()) elif space.is_kind_of(w_max, space.w_float): return self._rand_float(space, w_max) elif space.is_kind_of(w_max, space.getclassfor(W_RangeObject)): return self._rand_range(space, w_max) else: return self._rand_int(space, w_max) @classdef.singleton_method("rand") def method_singleton_rand(self, space, args_w): default = space.find_const(self, "DEFAULT") return space.send(default, space.newsymbol("rand"), args_w) def _rand_range(self, space, range): random = self.random.random() first = space.send(range, space.newsymbol("first")) last = space.send(range, space.newsymbol("last")) if space.is_true(space.send(range, space.newsymbol("include?"), [last])): last = space.send(last, space.newsymbol("+"), [space.newint(1)]) diff = space.send(last, space.newsymbol("-"), [first]) offset = space.send(diff, space.newsymbol("*"), [space.newfloat(random)]) choice = space.send(offset, space.newsymbol("+"), [first]) if (not space.is_kind_of(first, space.w_float) and not space.is_kind_of(last, space.w_float)): choice = space.send(choice, space.newsymbol("to_i")) return choice def _rand_float(self, space, float): random = self.random.random() max = Coerce.float(space, float) if max <= 0: raise space.error(space.w_ArgumentError, "invalid argument") return space.newfloat(random * max) def _rand_int(self, space, integer): random = self.random.random() max = Coerce.int(space, integer) if max <= 0: raise space.error(space.w_ArgumentError, "invalid argument") else: return space.newint(int(random * max))
def entry_point(argv): seed = int(time.time())^(os.getpid()<<16) rnd = Random(seed) for i in range(50): print(rnd.randint(1,10)) return 0
def method_srand(self, space, args_w): self.random = Random()
import math import sys from rpython.rlib import rfloat, jit from rpython.rlib.rarithmetic import r_uint, intmask, ovfcheck from rpython.rlib.rstring import StringBuilder from rpython.rlib.objectmodel import we_are_translated from hippy.objects.base import W_Root from hippy.objects.boolobject import W_BoolObject from hippy.objects.intobject import W_IntObject from hippy.objects.floatobject import W_FloatObject from hippy.builtin import wrap, Optional, LongArg from rpython.rlib.rrandom import Random _random = Random() RANDMAX = 0x7fffffff MAX_BITS = sys.maxint.bit_length() # == 31 or 63 @wrap(['space', W_Root], name="abs") def _abs(space, w_obj): return w_obj.abs(space) @wrap(['space', float]) def acos(space, d): """ acos - Arc cosine """ try: return space.wrap(math.acos(d)) except OverflowError:
def entry_point(argv): seed = int(time.time()) ^ (os.getpid() << 16) rnd = Random(seed) for i in range(50): print(rnd.randint(1, 10)) return 0