Can I specify a numpy dtype when generating random values?

前端 未结 3 652
粉色の甜心
粉色の甜心 2020-12-30 20:21

I\'m creating a numpy array of random values and adding them to an existing array containing 32-bit floats. I\'d like to generate the random values using the sa

3条回答
  •  再見小時候
    2020-12-30 20:52

    Q: is it possible to specify a dtype for random numbers when I create them.

    A: No it isn't. randn accepts the shape only as randn(d0, d1, ..., dn)

    Simply try this:

    x = np.random.randn(10, 10).astype('f')
    

    Or define a new function like

    np.random.randn2 = lambda *args, dtype=np.float64: np.random.randn(*args).astype(dtype)
    x = np.random.randn2(10, 10, dtype='f')
    

    If you have to use your code on the post, try this code instead

    x = np.zeros((10, 10), dtype='f')
    x[:] = np.random.randn(*x.shape)
    

    This assigns the results of randn to the memory allocated by np.zeros

提交回复
热议问题