mercredi 30 mai 2018

Generating random numbers while using itertools product

I am using a generator function to create ordered lists of numbers along side itertools.product in order to create every possible paring of said numbers:

def gen(lowerBound, upperBound, stepSize = 1):
    for steppedVal in np.arange(lowerBound, upperBound, stepSize):
        yield steppedVal

for vectors in it.product(gen(3,6), gen(10,30,5)):
    print(vectors)

Which as expected produces a data set like this one:

(3, 10)
(3, 15)
(3, 20)
(3, 25)
(4, 10)
(4, 15)
(4, 20)
(4, 25)
(5, 10)
(5, 15)
(5, 20)
(5, 25)

However my problem lies in the next step. I want to add a clause to generator function to use a random number within a range instead of the stepped values. When I try the following:

def gen(useRandom, lowerBound, upperBound, stepSize = 1):
    if useRandom:
        randomVal = random.uniform(lowerBound, upperBound)
        yield randomVal
    else:
        for steppedVal in np.arange(lowerBound, upperBound, stepSize):
            yield steppedVal

for vectors in itertools.product(gen(True,3,6), gen(False,10,30,5)):
    print(vectors)

I get this, which is not what I want:

(4.4163620543645585, 10)
(4.4163620543645585, 15)
(4.4163620543645585, 20)
(4.4163620543645585, 25)

How could I modify this code so that each random number in this data set is unique without having to alter the data set after the fact as that adds huge compute overhead. (The actual data set contains a dozen or so variables with 10-20 steps each).




Aucun commentaire:

Enregistrer un commentaire