4

I am somewhat confused about how to use numpy.random to generate random values from a give distribution, say, binomial. I thought it would be

import numpy as np
np.random.binomial(10, 0.3, 5)

However, NumPy reference page shows something like

from numpy.random import default_rng
rg = default_rng()
rg.binomial(10, 0.3, 5)

Both seem to be working well. Which one is the correct or better way? What is the difference if there is any?

JACKY88
  • 3,391
  • 5
  • 32
  • 48

2 Answers2

7

The first block of code uses a numpy.random.* function. numpy.random.* functions (including numpy.random.binomial) make use of a global RandomState object which is shared across the application.

The second block of code creates a pseudorandom generator object with default_rng() and uses that object to generate pseudorandom numbers without relying on global state.

Note that numpy.random.binomial (in addition to other numpy.random.* functions) is now a legacy function as of NumPy 1.17; NumPy 1.17 introduces a new pseudorandom number generation system, which is demonstrated in the second block of code in your question. It was the result of a proposal to change the RNG policy. The desire to avoid global state was one of the reasons for the change in this policy.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • Thanks. Do you mean the second block is going to replace the first block in the future? – JACKY88 Jan 14 '20 at 13:01
  • Not exactly. The changed RNG Policy doesn't say that `numpy.random.*` functions (including `numpy.random.binomial`) are obsolete. Rather, in most cases, they should be avoided whenever reproducible "randomness" is desired, with unit tests being a possible exception. See the [RNG Policy](https://github.com/numpy/numpy/blob/master/doc/neps/nep-0019-rng-policy.rst#numpyrandom) for more information. – Peter O. Jan 14 '20 at 13:48
-2
import random
random.choice([2,44,55,66])

A crucial thing to understand about the random choice method is that Python doesn't care about the fundamental nature of the objects that are contained in that list.