0

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.

2 Answers 2

1

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%

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.