Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big array with random numbers with python

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

like image 347
gdlm Avatar asked Aug 28 '12 21:08

gdlm


People also ask

How do you fill an array with random numbers in Python?

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.

How do you get 20 random numbers in Python?

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).

How do you generate a random large number in Python?

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.

How do you assign a random value to an array in Python?

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.


2 Answers

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]
  • when using random.sample, the equality len(population) >= k must hold
like image 71
marchelbling Avatar answered Oct 12 '22 12:10

marchelbling


You 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.

like image 24
Emanuel Fontelles Avatar answered Oct 12 '22 12:10

Emanuel Fontelles