Differences between standard random modules and numpy.random

Asked 2 years ago, Updated 2 years ago, 63 views

I'd like to use python to generate random numbers, but I checked and found that there is a way to use the standard random module and numpy.random. What is the difference between the random number generation?

python numpy

2022-09-30 17:27

3 Answers

Both Python standard random and numpy.random generate pseudo-random numbers and use the Mersenne Twister as the random number generator.The Melsenu Twister can quickly create statistically acceptable pseudorandom numbers.However, because it is predictable because it is generated by a linear gradualization formula, it is recommended that you use the secret module for security purposes.

Python document 9.6.random---Generating Pseudo-Random Numbers
Numpy Doc Random sampling(numpy.random)

The standard random is also created in the C language, so the processing speed remains the same.If you use arrays like Numpy or Pandas, using numpy.random is more convenient because you can easily create random arrays like np.random.random(1000), and the array processing is faster.On the other hand, if you don't want to use an array, you don't have to import numpy and use the standard random.For your information, I will list the processing time on Jupiter.

%%timeit
a = 0
for i in range (10000):
  a+=random.random() 

1000 loops, best of 3:1.12 ms per loop

%%timeit
a = 0
for x in np.random.random(10000):
  a+=x

1000 loops, best of 3:1.12 ms per loop

The difference between Differences between numpy.random and random.random in Python is that numpy.random.seed() is not thread safe, but random.random.seed() is written in the threaded document.

9.6.6. About Repeatability <

It may be useful to be able to reproduce a given sequence from a pseudo-random number generator.By reusing seed values, you can reproduce the same sequence for each run unless multiple threads are running.


2022-09-30 17:27

According to this article, numpy is faster when generating a large number of random numbers and performing the process.
https://qiita.com/yubais/items/bf9ce0a8fefdcc0b0c97


2022-09-30 17:27

There is an article like this, so please refer to it
There seems to be a big difference in the number of random numbers generated
http://python-remrin.hatenadiary.jp/entry/2017/04/26/233717


2022-09-30 17:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.