I'm doing a question that requires me to use random() to generate a number between 0 to 9999 with equal probability. I know I can scale random() by multiplying it, but I'm getting mainly 4 digit numbers. Anyone knows what to do?
Asked
Active
Viewed 7,345 times
-6
Sociopath
- 12,395
- 17
- 43
- 69
stevehaines
- 1
- 1
- 2
-
3out of 0-9999 numbers, 1000-9999 are 4 digit numbers. So, it is highly probable that you get a 4 digit number when each number is equally probable. – Gimhani Sep 05 '18 at 09:17
-
*I know I can scale random() by multiplying it*: You should not do that ;) – hellow Sep 05 '18 at 09:18
-
1Btw: welcome to Stackoverflow. The reason you got a downvote is, because there are plenty of questions about generating a random number between x and y, so you should search for your question first, before blindly asking. Please take yourself some time to take [the tour](https://stackoverflow.com/tour) and read [how to ask a good question](https://stackoverflow.com/help/how-to-ask) – hellow Sep 05 '18 at 09:21
-
I actually tried to search for a similar question but I couldn't. – stevehaines Sep 05 '18 at 09:47
4 Answers
5
Use randint.
>>> import random as r
>>> r.randint(0,9999)
6935
>>> r.randint(0,9999)
5550
>>>
Black Thunder
- 6,215
- 5
- 27
- 56
2
Suggestion, assuming you want a random integer:
from random import randint
print(randint(0,9999))
meissner_
- 515
- 6
- 10
2
You are getting 4-digit numbers because they are 90% of your range, so it's expected. However, you don't need to scale random(), instead use random.randint.
blue_note
- 25,410
- 6
- 56
- 79
1
import numpy as np
# retruns n numbers with uniform(equal) propability between a and b
# thus for each x in arr: a <= x < b
arr = np.random.uniform(a, b, n)
If you want them to be integers
arr = np.round(arr).astype(int)
see also here: np.random.uniform
rikisa
- 191
- 1
- 9
-
There is no need to use an external library like numpy, to generate a random number, but yes, this should work – hellow Sep 05 '18 at 09:19