so rn I am working in asynchronous python, and i have to deal with random number. Problem is that, for numbers between 0 and 4, I get the same numbers very often, like as follows :
3 2 0 2 4 0 1 4 2 1 4 2 1 3 2 3 2 2 2 1 0 3 2 2 2 0 0 4 3 0 3 4 4 0 3 3 3 3 2 4 4 4 0
of course there is only five possibilities but look at the end, i got 4 number 3 in a row, which is roughly 1/625 chance, and we don't talk about the times i get the same number 3 times in a row.
My code looks like this :
when async ready :
random.seed(time.time())
async event:
index = random.randint(0,4)
async.send(someList[index])
Also it is a discord bot so the code runs continuously, so the seed is only donc once if that matters
CodePudding user response:
Without a more complete, yet minimal example, we cannot be sure if the code you use works as intended, but in a 42 element long list, it is quite common to have a value repeated 4 times in a row. Check the following code that generates 1000 times a 42 long random list, checks the longest repetition in each list, and counts how often happens it.
import random
import matplotlib.pyplot as plt
length_of_longest = []
for j in range(1000):
random.seed(j)
rndstr = "".join([str(random.randint(0, 4)) for _ in range(42)])
for i in range(1, 42):
total = 0
for my_str in "01234":
for_my_str = rndstr.count(my_str*i)
total = for_my_str
if total == 0:
length_of_longest.append(i-1) # this length was not found
break
# plot the results
fig, ax = plt.subplots()
ax.set_xticks([i 0.5 for i in range(8)], labels=range(8))
fig.patch.set_facecolor('white')
plt.hist(length_of_longest,bins=range(0,max(length_of_longest) 2))
This produces the following plot:
The x-axis tells how often was the longest repetition x long (e.g. at x=5, then there was a 11111 or 33333 or ... in the sequence), and y tells how many series were found with this property out of 1000.
It can be seen that in around 15%-20% of the cases, the length of the longest sequence is 4, but it can also occur a couple of times out of 1000, that the same value is chosen 7 times in a row.

