pythonnumpyrandom

How to fill an existing numpy array with random normally distributed numbers


I would like to generate many batches of random numbers. I only need access to one batch at a time. Naively, I could repeatedly call np.random.randn(size), but that allocates an array each time. For performance, I would like to populate an existing array with something like np.random.randn(size, out=arr), but that form of randn doesn't seem to exist. How can I fill an existing array with random numbers?


Solution

  • Here is one approach that reuses the array in every call of rng.standard_normal:

    import numpy as np
    
    rng = np.random.default_rng()
    
    size = 1000
    arr = np.empty(size)
    rng.standard_normal(size, out=arr)