How to Generate N random numbers in Python 3 between 0 to infinity
Solution 1
To paraphrase Wittgenstein, the limits of your machine is the limits of your language. i.e. There is no such thing as infinity in computers/computation world. You can get the largest positive integer supported by your machine using sys.maxsize
(sys.maxint
in python 2) and pass it to random.randint
function:
>>> import sys
>>> sys.maxsize
9223372036854775807
>>> random.randint(0,sys.maxsize)
7512061515276834201
And for generating multiple random numbers you can use a list comprehension like following:
>>> N = 10
>>> [random.randint(0,sys.maxsize) for _ in range(N)]
[3275729488497352533, 7487884953907275260, 36555221619119354, 1813061054215861082, 619640952660975257, 9041692448390670491, 5863449945569266108, 8061742194513906273, 1435436865777681895, 8761466112930659544]
For more info about the difference of sys.maxint
and sys.maxsize
in python 2.X and 3.X:
The
sys.maxint
constant was removed, since there is no longer a limit to the value of integers. However,sys.maxsize
can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same assys.maxint
in previous releases on the same platform (assuming the same build options).
Solution 2
I think you probably need to rethink what it is you're trying to do with the random number you want. In particular, what distribution are you sampling the number from? If you want your random numbers uniformly distributed (equal probability of each number being chosen), you can't: you'd need an infinite amount of memory (or time, or both).
Of course, if you allow for non-uniform distributions, here are some random numbers between 1 and (roughly) the largest float
my system allows, but there are gaps due to the way that such numbers are represented. And you may feel that the probability of "large" numbers being selected falls away rather quicker than you'd like...
In [254]: [int(1./random.random()) for i in range(10)]
Out[254]: [1, 1, 2, 1, 1, 117, 1, 3, 2, 6]
Billy Cole
Mistakes train your mind Sacrifice trains your soul -Billy Cole, 2016, whilst trying to get to sleep
Updated on August 01, 2022Comments
-
Billy Cole about 1 year
How do I generate n random numbers in python 3? n is a to be determined variable. preferably natural numbers (integers > 0), All answers I've found take random integers from a range, however I don't want to generate numbers from a range. (unless the range is 0 to infinity)