Reputation: 437
I want to combine two random number generator.
I want to generate size = 20 random integers between [-5,5] and a fixed integer -999.
I tried following code:
from random import randint, choice
import numpy as np
np.random.seed(1)
dd = np.array([choice([randint(-999,-999),randint(-5,5)]) for _ in range(20)])
print(dd)
Result:
[-999 -999 -999 -4 -999 -999 -4 -999 -999 3 5 -3 2 0
-1 -999 -999 -5 -999 -4]
Is there any better way to generate random integers? The result with current code has many -999 due to same upper and lower limit.
Upvotes: 0
Views: 968
Reputation: 99
Your solution yields approximately 50% of the cases -999 and the rest a number in [-5, 5]. This is because choice has to choose between -999 and X (where X is a number previously defined by randint, between -5 and 5). If you want every number to have the same probability of being chosen try the following proposed solution:
lst = [i for i in range(-5, 6)] + [-999]
dd = [choice(lst) for _ in range(20)]
The probability that a number in the list lst is chosen by choice is 1/12 ~ 8%
Upvotes: 1
Reputation: 11
Currently its choosing between -999 and random number between -5 and 5 on each iteration. So you would expect 50% of results to be -999.
One way would be to first define a list of choices
choices = list(range(-5,5))+ [-999]
Then, do the sampling using np.random.choice instead of a for loop list comprehension. Using size = 20 you can set how many to select.
dd = np.random.choice(choices, size = 20)
Upvotes: 0