mercredi 17 novembre 2021

Generate two lists of random numbers to obtain a fixed sum

I need to generate two lists (let's call them X and Y) that sum to a specific number.

The function I need to create will take as inputs length of X and Y and the sum.

Then it creates random positive numbers for X and negative numbers for Y and normalizes them to sum to the number I want.

I've tried doing it like this:

def extractAmount(ina, outa, balance):
    # ina: length of X, outa: length of Y, balance: the number I want
    valin = random.random((1, ina))  # X
    valout = -random.random((1, outa))  # Y
    val = np.concatenate([valin[0], valout[0]])
    valf = (np.round(val / abs(np.sum(val)) * abs(balance))).tolist() 
    return valf

The code works both for positive and negative numbers as balance, how could I improve it to work also if balance == 0?

If I do extractAmount(2, 3, 100), the output is [49.0, 350.0, -44.0, -68.0, -186.0], my problem is that if I do extractAmount(2, 3, 0), it returns [0.0, 0.0, 0.0, 0.0, 0.0] while I need it to be random values, not all zeros.




Aucun commentaire:

Enregistrer un commentaire