Random number generator



  • I had this idea of creating a finite state machine which makes transitions between three states. So, I needed to generate random numbers between 0 and 1. Is there such module for LoPy. I used randint(0,1) but it doesn't work. Any suggestions?



  • @livius Thanks I tried it and it works. I had another question if you could give some suggestion. I have been trying to take the last four bytes of the mac address as source and destination address to send data from one Lopy to a second LoPy. I created a package header as the following:

    _LORA_PKG_FORMAT = "LL%ds"
    _LORA_ACK_FORMAT = "LLB"
    SRC_MAC_ADDR = ubinascii.hexlify(lora.mac().strip()[-4:])

    Destination address
    DEST_MAC_ADDR = b'9cc15603'

    ** pkg = struct.pack(_LORA_PKG_FORMAT, DEST_MAC_ADDR, SRC_MAC_ADDR, msg)

    But when I try running it complains saying ValueError: unsupported format for the line with **. what do you think I am doing wrong?



  • i see that code work on my Wipy2 without any modification :)
    below results

    Random()
    0.8462145
    >>> Random()
    0.4143322
    >>> Random()
    0.1052132
    >>> Random()
    0.7745724
    >>> Random()
    0.4098172
    >>> Random()
    0.2059813
    >>> Random()
    0.3866896
    

    and bigger test:

    sum=0
    >>> ile=0
    >>> for i in range(1,1000000):
    ...     sum+=Random()
    ...     ile+=1
    ...
    >>> sum
    499948.5
    >>> ile
    999999
    >>> sum/ile
    0.499949
    

    realy near to 0.5 - as you can see it is ok :)



  • @timeb
    you can try something like this
    https://docs.pycom.io/pycom_esp32/library/ucrypto.html?highlight=getrandbits#ucrypto.crypto.getrandbits

    please be patient that i write this from memory without any test - you should fix errors
    this is only concept

    def Random():
       r = crypto.getrandbits(32)
       return ((r[0]<<24)+(r[1]<<16)+(r[2]<<8)+r[3])/4294967295.0
    

Log in to reply
 

Pycom on Twitter