Home > OS >  How to create a set of random numbers with numpy
How to create a set of random numbers with numpy

Time:01-21

My requirement is to create a set of random numbers. I know the set size and the random number range. Therefore:

import random
def makeset(lo, hi, ss):
  s = set()
  while len(s) < ss:
    s.add(random.randint(lo, hi))
  return s

I realise that certain combinations of lo, hi & ss could result in an impossible task but that's not in scope here.

I've started learning about numpy and wondered if that module offered something that could do this in a single step - i.e., no explicit loop.

But I can't find anything in the documentation. Maybe it's not there.

Any thoughts?

CodePudding user response:

You could use np.random.choice without replacement as follows:

import numpy as np
gen = np.random.Generator(np.random.PCG64())
def with_numpy_gen(lo, hi, ss):
  return gen.choice(np.arange(lo, hi   1), ss, replace=False)

CodePudding user response:

numpy.random.random(size=None)

  •  Tags:  
  • Related