I need to generate a big array (or list) with random numbers ( 10⁵ numbers) . I was trying like that:
vet = random.sample(range(10),100000)
But when I try to run :
vet = random.sample(range(10),10000)
File "/usr/lib/python2.7/random.py", line 320, in sample raise ValueError("sample larger than population") ValueError: sample larger than population
Any solution?
tkns
To create a matrix of random integers in Python, randint() function of the numpy module is used. This function is used for random sampling i.e. all the numbers generated will be at random and cannot be predicted at hand.
Use a random. randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random. randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).
Random integers can be generated using functions such as randrange() and randint(). Let us first take a look at randint(). In case you want to generate numbers in intervals, you can use the randrange() function.
The choice() method allows you to generate a random value based on an array of values. The choice() method takes an array as a parameter and randomly returns one of the values.
What you want is
[random.random() for _ in xrange(100000)]
From the random module documentation:
random.sample(population, k) Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
so when calling random.sample(range(10), 100000)
you're trying to extract 100000 unique elements in a sequence of length 10 which obviously can't work.
Note that
random.random()
returns a floating value between [0 ; 1)random.randrange([start], stop[, step])
returns a random element from the sequence range([start], stop[, step])
random.randint(a, b)
returns an integer value in [a ; b]random.sample
, the equality len(population) >= k
must holdYou can you the numpy function and create an array with N space filled with a random number
import numpy as np
vector_size = 10000
one_dimensional_array = np.random.rand(vector_size)
two_dimensional_array = np.random.rand(vector_size, 2)
tree_dimensional_array = np.random.rand(vector_size, 3)
#and so on
numpy.random.rand
You can create matrix of random numbers using the function below and arrays also.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With