lundi 20 janvier 2020

Randomize subject to a constraint

I have a vector x = [0.90171326, 0.01464065, 1.17370892], and I want to generate some random weights (w = [w1, w2, w3]), whereby the absolute sum of the weighted x vector would be less than some given y value. Any smart way to do this? Thanks!

This is what I tried:

def randomize(attempts, n, x): 
    for attempt in range(attempts):
        w = [np.random.randint(-500000, 500000) for i in range(n)]
        total = sum(w * x)
        if abs(total) < 300000:
            return w
        else:
            attempt += attempt

However my function return None if the condition is not fulfilled instead of trying again. It only returns if I am lucky and I hit the conditon at first attempt




Aucun commentaire:

Enregistrer un commentaire