Fastest Way to generate 1,000,000+ random numbers in python

后端 未结 6 705
时光取名叫无心
时光取名叫无心 2020-12-13 19:28

I am currently writing an app in python that needs to generate large amount of random numbers, FAST. Currently I have a scheme going that uses numpy to generate all of the n

6条回答
  •  旧巷少年郎
    2020-12-13 20:07

    Try r = 1664525*r + 1013904223
    from "an even quicker generator" in "Numerical Recipes in C" 2nd edition, Press et al., isbn 0521431085, p. 284.
    np.random is certainly "more random"; see Linear congruential generator .

    In python, use np.uint32 like this:

    python -mtimeit -s '
    import numpy as np
    r = 1
    r = np.array([r], np.uint32)[0]  # 316 py -> 16 us np 
        # python longs can be arbitrarily long, so slow
    ' '
    r = r*1664525 + 1013904223  # NR2 p. 284
    '
    

    To generate big blocks at a time:

    # initialize --
    np.random.seed( ... )
    R = np.random.randint( 0, np.iinfo( np.uint32 ).max, size,  dtype=np.uint32 )
    ...
    R *= 1664525
    R += 1013904223
    

提交回复
热议问题