Seeding random number generator



  • Hello, I'm looking for a way to seed the pseudo number generator (machine.rng() or uos.urandom()). There must be a way to do this but I couldn't figure it out how.



  • @robert-hh Nice! Thank you Robert!



  • @Valimir-Cool The urandom module of the main MP version is missing. Below you have a Python port of the MicroPython PRNG with just two of the functions. More can easily added:

    # Yasmarang random number generator
    # by Ilya Levin
    # http://www.literatecode.com/yasmarang
    # Public Domain
    
    class PRNG:
        def __init__(self):
            self.seed()
    
        def yasmarang(self):
            self.yasmarang_pad = (self.yasmarang_pad + self.yasmarang_dat + self.yasmarang_d * self.yasmarang_n) & 0xffffffff
            self.yasmarang_pad = ((self.yasmarang_pad << 3) + (self.yasmarang_pad >> 29)) & 0xffffffff
            self.yasmarang_n = self.yasmarang_pad | 2
            self.yasmarang_d ^= ((self.yasmarang_pad << 31) + (self.yasmarang_pad >> 1)) & 0xffffffff
            self.yasmarang_dat ^= (self.yasmarang_pad ^ (self.yasmarang_d >> 8) ^ 1) & 0xff
            return (self.yasmarang_pad ^ (self.yasmarang_d << 5) ^ (self.yasmarang_pad >> 18) ^ (self.yasmarang_dat << 1)) & 0xffffffff
    
        def get_int(self):
            return self.yasmarang()
    
        def seed(self, seed = 0xeda4baba):
            self.yasmarang_pad = seed
            self.yasmarang_n = 69
            self.yasmarang_d = 233
            self.yasmarang_dat = 0
    


  • @robert-hh Thanks- It's quite disapointing having a pseudo rng without the possibillity of manually setting the seed... And I can't really see any reason for not giving this possibility that IMO is quite important.



  • This post is deleted!


  • @Valimir-Cool There is no API provided for seeding. So you have to implement your own RNG. The internal pseudo-rng is seeded by a combination of the unique chip ID and the actual time.


Log in to reply
 

Pycom on Twitter