[Python] Generate 4 random numbers between -1.0 and 1.0 such their sum is 1 using python

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying generate 4 random numbers between -1.0 and 1.0 such that their sum is 1 using python. I initially looked at the dirichlet function in numpy but that only works for positive numbers. One other way I can think of is:

    def generate_random_numbers():
    numbers = np.random.uniform(-1.0, 1.0, 3)
    last_number = 1 - np.sum(numbers)
    if -1.0 <= last_number <= 1.0:
    return np.append(numbers, last_number)
    else:
    return generate_random_numbers()


    However its not that efficient. Any other way to do this?

    Continue reading...

Compartilhe esta Página