[Python] How can I quickly generate a (large) list of random numbers given a list of seeds as...

Discussão em 'Python' iniciado por Stack, Setembro 26, 2024.

  1. Stack

    Stack Membro Participativo

    I need to make a function that takes in an array of integers and returns a list of random numbers with the same length as the array. However, there is the restriction that the output random number corresponding to a given entry in the input array should always be the same based upon that entry.

    For example, if input_a given below returns the following:

    > input_a = np.array([1, 2, 3, 4, 5])
    > random_array(input_a)
    [0.51689016 0.62747792 0.16585436 0.63928942 0.30514275]


    Then input_b given below should return the following:

    > input_b = np.array([3, 2, 3])
    > random_array(input_b)
    [0.16585436 0.62747792 0.16585436]


    Note that the output numbers that correspond to an input of 3 are all the same, and likewise for those that correspond to an input of 2. In effect, the values of the input array are used as seeds for the output array.

    The main issue is that the input arrays may be very big, so I'd need something that can do the operation efficiently.

    My naive implementation is as follows, making a list of random number generators with the input array as seeds.

    import numpy as np

    def random_array(input_array):
    rng_list = [np.random.default_rng(seed=i) for i in input_array]
    return [rng.random() for rng in rng_list]

    input_a = np.array([1, 2, 3])
    input_b = np.array([3, 2, 3])

    print(random_array(input_a)) # [0.5118216247002567, 0.2616121342493164, 0.08564916714362436]
    print(random_array(input_b)) # [0.08564916714362436, 0.2616121342493164, 0.08564916714362436]


    It works as intended, but it's terribly slow for what I need it to do - unsurprising, given that it's doing a loop over array entries. This implementation takes 5 seconds or so to run on an input array of length 100,000, and I'll need to do this for much larger inputs than that.

    How can I do this but more efficiently?

    Continue reading...

Compartilhe esta Página