4

I am using the RevitPythonShell and after a frustratingly long search for a bug in my code, I found that the problem was due to the random module acting weird. Almost all the functions in the random module seem to leave half of the possibilities untouched.

random.sample is only sampling the first half of the list. random.uniform is generating numbers less than the average of the two bounds. random.random() is only generating numbers between 0 and 0.5.

Below code is form the revitpythonshell terminal. Can anyone help me understand what is going on ?

>>> import random
>>> #random number in the range [0.0, 1.0)
>>> for _ in range(1000):
...     if random.random() >= 0.5: print("hello !!")
... 
>>> # nothing got printed !!!
>>> max = 0
>>> for _ in range(1000):
...     rand = random.random()
...     if rand > max: max = rand
... 
>>> max
0.499520565070528
>>> # looks like the random values are being capped at 0.5 !!
>>> 
>>> nums = list(range(10))
>>> for _ in range(1000): 
...     if random.sample(nums, 1)[0] >= 5: print("hello")
... 
>>> # nothing got printed !!
>>> # half of the range of possibilities goes untouched for some reason
>>> a = 3.5
>>> b = 4.75
>>> half = (a+b)/2
>>> for _ in range(1000):
...     if random.uniform(a,b) > half: print("Hello !!!")
... 
>>> # nothing got printed !! all the values are less than half !!!
>>> #looks like all the functions of the random module have this behavior
>>> 
  • 3
    Well spotted !! This is an ironpython issue (RevitPythonShell is not guilty). A workaround for `random.random()` is to used `random.WichmannHill().random()`, but this problem requires a solid fix – PRMoureu Jun 26 '17 at 08:59
  • 1
    The overall distribution still looks uniform from 0 to 0.5. So `random.uniform(0,2)` also works fine to produce a random float in [0,1[ but that is not such a good news because it means that every other function depending on the `random.random()` function will be wrong as well... – Prolix Oct 25 '17 at 07:35
  • @PRMoureu This fix and some maybe related erroneous behavior are described on the [git](https://github.com/IronLanguages/ironpython2/issues/231). But I did not test if it is indeed fixed in the latest master... – Prolix Oct 25 '17 at 07:48
  • @Prolix Thanks for the update, i didn't try it neither, i may find some time in the week to confirm – PRMoureu Oct 25 '17 at 10:50

0 Answers0