Creating same random number sequence in Python, NumPy and R

后端 未结 2 419
小鲜肉
小鲜肉 2020-12-01 11:02

Python, NumPy and R all use the same algorithm (Mersenne Twister) for generating random number sequences. Thus, theoretically speaking, setting the same seed should result i

相关标签:
2条回答
  • 2020-12-01 11:30

    I realize this is an old question, but I've stumbled upon the same problem recently, and created a solution which can be useful to others.

    I've written a random number generator in C, and linked it to both R and Python. This way, the random numbers are guaranteed to be the same in both languages since they are generated using the same C code.

    The program is called SyncRNG and can be found here: https://github.com/GjjvdBurg/SyncRNG.

    0 讨论(0)
  • 2020-12-01 11:44

    use rpy2 to call r in python, here is a demo, the numpy array data is sharing memory with x in R:

    import rpy2.robjects as robjects
    
    data = robjects.r("""
    set.seed(1)
    x <- runif(5)
    """)
    
    print np.array(data)
    
    data[1] = 1.0
    
    print robjects.r["x"]
    
    0 讨论(0)
提交回复
热议问题