Ekaitz
Ekaitz

Reputation: 1

How can i get multiple different random numbers at the same time?

I wanna make a pong game with two balls, so I need two random numbers for the initial direction of each ball. As far as I know python uses the hour as seed, so as long as both numbers are asked in a same time (just some ms later that don't affect at all), both random numbers will be the same. How can I get two different random numbers at the same time?

I tried to get to different random numbers but both numbers were the same. Therefore, both balls took the same direction.

Upvotes: -4

Views: 60

Answers (1)

xingern
xingern

Reputation: 21

Depending on your code, the reason for the duplicate numbers could be many reasons. The module does not utilize hours as the only timestamp, but also some higher precisions, see the following example:

import random

a = random.random()
b = random.random()
print(a, b)

0.5273803990480128 0.16814494622242826

However, one can ensure that the same same number gets produced if a new seed is called again and again:

import random

for i in range(3):
    random.seed(1)
    num = random.randint(1, 100)
    print(num)

18 18 18

Specifically for your game, you should only call a seed once (in cases where you want reproducibility). This post also summarizes the answer to your question.

Note: This is my first time answering questions so feedback is greatly appreciated.

Upvotes: 2

Related Questions