the_t_test_1
the_t_test_1

Reputation: 1263

How to generate multiple random numbers in Python to a sufficiently 'random' degree

I hope this question is sufficiently question-worthy and that I haven't missed the point. I understand that there are likely multiple answers - I will mark the best one I get correct, but if this is not an OK question to ask then please say and I will delete as appropriate.

If I am using python scripts where there's lots of (more than one) random numbers required, e.g.

from random import randrange

number1 = randrange(10)
number2 = randrange(10)
number3 = randrange(10)

print number1, number2, number3

...then is randrange the best way to do it? Specifically, how random actually is it? I feel like I notice that it has a sort of... bias?

Like, repeatedly seems to get the same values.

I might be imagining it.

But obviously I know computers don't do random well (at all), and I was wondering how this module is even seeded or whatever...

Is there a better way to generate my random numbers? Like a module that's "more random" or a way to give it a "more random" seed?

Upvotes: 1

Views: 2220

Answers (3)

Arash Rohani
Arash Rohani

Reputation: 1014

I don't know much about the differences of random or pseudo-random but if you run the same randrange command for 10 million times you can see that the percentages of repeats are very close. So I don't think you can spot any non-random behavior just by printing the generated numbers and looking at them (not in this case at least).

from random import randrange
number_of_repeats = [0,0,0,0,0,0,0,0,0,0]
percentage = {}
loop_count = 10000000
for _ in range(loop_count):
    number_of_repeats[randrange(10)]+=1
for num,i in enumerate(number_of_repeats):
    percentage[num] = (i/loop_count)*100
print(percentage)

Upvotes: 1

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38932

Better to use SystemRandom for better unpredictability. randrange is a pseudorandom number generator which uses Mersenne Twister.

from random import SystemRandom

srand = SystemRandom()

num1 = srand.choice(range(10))
num2 = srand.choice(range(10))
num3 = srand.choice(range(10))

print num1, num2, num3

Upvotes: 1

Yann Vernier
Yann Vernier

Reputation: 15877

This is heavily dependent on what degree of randomness you're looking for. Python provides os.urandom with the intent of cryptographic use; but that reads from /dev/urandom, not /dev/random, so it might not be random enough for some extreme cases (discussion on unix & linux stack exchange). The secrets module was developed for a clearer choice, while the random module is clearly pseudo-random. That pseudo-randomness is usually enough, provided the seed is not repeated (doing that is helpful for things like repeatable tests or regenerating identical procedurally generated games, which is why we have getstate and setstate).

In general, our ability to find patterns in randomness far exceeds our ability to recognize randomness.

Upvotes: 1

Related Questions