12

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

gdlm
  • 343
  • 2
  • 6
  • 11
  • 7
    Considering the size of that list, you might want to consider an array library like [numpy](http://numpy.scipy.org/): `import numpy; vet = numpy.random.randint(0, 10, 10000)` – Snowball Aug 28 '12 at 21:58

3 Answers3

31

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
ThisClark
  • 14,352
  • 10
  • 69
  • 100
marchelbling
  • 1,909
  • 15
  • 23
13

I think you're after something like this:

vet = [random.randint(1,10) for _ in range(100000)]
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
2

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.

Emanuel Fontelles
  • 864
  • 1
  • 11
  • 14