bbcmicrobit / micropython

Port of MicroPython for the BBC micro:bit
https://microbit-micropython.readthedocs.io
Other
595 stars 287 forks source link

random numbers #778

Closed rhubarbdog closed 1 year ago

rhubarbdog commented 1 year ago

why is random.random() in python 3 returning a number in range [0, 1), where as in micropython it is in range [0, 1]?

microbit-carlos commented 1 year ago

In theory it should only generate numbers from 0 to 1, exclusive of 1. Have you seen it generate the value 1.0? Would you be able to provide an example when that might happen? It is possible the REPL does some rounding when displaying numbers, did you see this result in the REPL or inside any function you've run?

rhubarbdog commented 1 year ago

it's in readthedocs on this page https://microbit-micropython.readthedocs.io/en/v2-docs/tutorials/random.html, but else where in the same document it says the range is [0, 1) on this page https://microbit-micropython.readthedocs.io/en/v2-docs/random.html, now i've seen this it looks like a problem with the docs

dpgeorge commented 1 year ago

Yes you are right, it looks like this sentence needs to be changed:

This only returns values between 0.0 and 1.0 inclusive

dpgeorge commented 1 year ago

For completeness, here is a test I ran to check the output of random.random():

import array, random
while 1:
    r = random.random()
    if r > 0.99999:
       print(r, r<1, bytes(array.array('f', [r])))

The output is something like this:

0.9999929 True b'\x8a\xff\x7f?'
0.9999938 True b'\x98\xff\x7f?'
0.9999932 True b'\x8e\xff\x7f?'
0.9999981 True b'\xe0\xff\x7f?'
0.9999969 True b'\xcc\xff\x7f?'
0.9999948 True b'\xa8\xff\x7f?'
0.9999928 True b'\x86\xff\x7f?'
0.9999924 True b'\x80\xff\x7f?'
0.9999985 True b'\xe6\xff\x7f?'
1.0 True b'\xfe\xff\x7f?'
0.9999948 True b'\xa8\xff\x7f?'
0.9999914 True b'p\xff\x7f?'
0.9999905 True b'`\xff\x7f?'
0.9999908 True b'f\xff\x7f?'
0.9999956 True b'\xb6\xff\x7f?'
0.9999953 True b'\xb2\xff\x7f?'

You can see it does print "1.0" sometimes, but that's just the output routines rounding the number up to 1. It's actually just a bit smaller than 1 as can be seen by the "True" output which is a comparison with 1. Also the bytes representation shows it's not exactly 1, but a bit less.

microbit-carlos commented 1 year ago

Great, thanks @rhubarbdog and @dpgeorge!

It looks like the API page is correct as well: https://microbit-micropython.readthedocs.io/en/v2-docs/random.html#random.random

I'll raise a PR to update the random tutorial page 👍

microbit-carlos commented 1 year ago