random.randint() not exists in esp8266 ?

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
VladVons
Posts: 58
Joined: Sun Feb 12, 2017 6:49 pm
Location: Ukraine

random.randint() not exists in esp8266 ?

Post by VladVons » Fri Feb 19, 2021 1:04 pm

in ESP32 there is a random.randint() function
in ESP866 no.

how to get any randomize value in ESP866 ?

Christian Walther
Posts: 129
Joined: Fri Aug 19, 2016 11:55 am

Re: random.randint() not exists in esp8266 ?

Post by Christian Walther » Fri Feb 19, 2021 2:02 pm

As far as I recall, random.getrandbits() is the only function available on ESP8266 (check help(random)). You can build anything else you need on top of that. Here’s a ready-to-use example.

VladVons
Posts: 58
Joined: Sun Feb 12, 2017 6:49 pm
Location: Ukraine

Re: random.randint() not exists in esp8266 ?

Post by VladVons » Fri Feb 19, 2021 3:38 pm

thanks Christian
got it

Andrewski
Posts: 1
Joined: Sat Feb 27, 2021 7:06 pm

Re: random.randint() not exists in esp8266 ?

Post by Andrewski » Sat Feb 27, 2021 7:10 pm

I found the below from this topic: viewtopic.php?t=6158

Code: Select all

import urandom

def randint(min, max):
    div = 0x3fffffff // span
    span = max - min + 1
    offset = urandom.getrandbits(30) // div
    val = min + offset
    return val

Christian Walther
Posts: 129
Joined: Fri Aug 19, 2016 11:55 am

Re: random.randint() not exists in esp8266 ?

Post by Christian Walther » Sun Feb 28, 2021 11:48 am

This doesn’t work for several reasons.
  • Lines are in the wrong order (variable is used before assignment).
  • It gives you values outside of the requested range (try with min = 0, max = 0x1fffffff, getrandbits(30) = 0x3fffffff).
  • It doesn’t give you a uniform distribution, some values are more likely than others.
The version on micropython-lib I linked above is correct.

Post Reply