-6

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?

Sociopath
  • 13,068
  • 19
  • 47
  • 75
stevehaines
  • 9
  • 1
  • 2
  • 3
    out 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
  • 1
    Btw: 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 Answers4

6

Use randint.

>>> import random as r
>>> r.randint(0,9999)
6935
>>> r.randint(0,9999)
5550
>>> 
Nouman
  • 6,947
  • 7
  • 32
  • 60
4

Suggestion, assuming you want a random integer:

from random import randint
print(randint(0,9999))
meissner_
  • 556
  • 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
  • 27,712
  • 9
  • 72
  • 90
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
  • 301
  • 2
  • 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