4

Need help in understanding the concept here - I have this code

import random
random.seed(a=57)

def run_round(info):
    random.seed(a=57)
    d = {}
    for i in info:
        performance_value = random.normalvariate(info[i][0], info[i][1])
        d[i] = performance_value
    return d
info = {'abc': (100, 5), 'bcd': (95, 5)}
print(run_round(info))

Now if I run this program 5 times in python3, the output is -

{'bcd': 86.51389158254244, 'abc': 105.76045089520113}
{'abc': 91.51389158254244, 'bcd': 100.76045089520113}
{'abc': 91.51389158254244, 'bcd': 100.76045089520113}
{'bcd': 86.51389158254244, 'abc': 105.76045089520113}
{'bcd': 86.51389158254244, 'abc': 105.76045089520113}

And in python2, the output is -

{'bcd': 86.51389158254244, 'abc': 105.76045089520113}
{'bcd': 86.51389158254244, 'abc': 105.76045089520113}
{'bcd': 86.51389158254244, 'abc': 105.76045089520113}
{'bcd': 86.51389158254244, 'abc': 105.76045089520113}
{'bcd': 86.51389158254244, 'abc': 105.76045089520113}

5 is just for reference, what I mean to say is that why is there a difference in values in python3, if I have given a seed which is same in certain cases.

Edit - tried with random.seed(a=57, version=1) and got this result -

{'abc': 91.51389158254244, 'bcd': 100.76045089520113} 
{'abc': 91.51389158254244, 'bcd': 100.76045089520113} 
{'abc': 91.51389158254244, 'bcd': 100.76045089520113} 
{'bcd': 86.51389158254244, 'abc': 105.76045089520113}                                                 
{'bcd': 86.51389158254244, 'abc': 105.76045089520113}  

I did not understand why there is a difference in results even when my seed remains the same.

hyades
  • 3,110
  • 1
  • 17
  • 36
  • 2
    Have you read [the documentation](https://docs.python.org/3/library/random.html#random.seed)? You can specify the `version` for `seed` in 3.x. – jonrsharpe Nov 28 '14 at 14:53
  • 2
    possible duplicate of [Why is seeding the random generator not stable between versions of Python?](http://stackoverflow.com/questions/11929701/why-is-seeding-the-random-generator-not-stable-between-versions-of-python) – jonrsharpe Nov 28 '14 at 14:54
  • 3
    @jonrsharpe that seems to accommodate changes within the 3.x release, but doesn't seem to offer backward compatibility to the 2.x releases. – Charles E. Grant Jul 08 '16 at 00:51
  • The problem is also in your use of a dictionary, I would guess. What if `info` is an `OrderedDict`? – jonrsharpe Jul 08 '16 at 06:28

0 Answers0