0
0
NumPydata~5 mins

np.random.default_rng() modern approach in NumPy - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is np.random.default_rng() used for?

np.random.default_rng() creates a new random number generator object. It is the modern way to generate random numbers in NumPy, replacing older functions like np.random.rand().

Click to reveal answer
beginner
How do you generate 5 random integers between 0 and 10 using default_rng()?
rng = np.random.default_rng()
random_ints = rng.integers(0, 10, size=5)

This creates 5 random integers from 0 up to (but not including) 10.

Click to reveal answer
intermediate
Why is default_rng() preferred over older NumPy random functions?

It provides better randomness quality, is easier to control with a seed, and avoids global state issues. It also supports new features and is the recommended approach since NumPy 1.17.

Click to reveal answer
beginner
How do you set a seed with default_rng() to get repeatable results?
rng = np.random.default_rng(42)

Using the same seed will produce the same sequence of random numbers every time.

Click to reveal answer
beginner
What method would you use with default_rng() to generate random floats between 0 and 1?

Use rng.random(size) to generate random floats in the range [0, 1).

Click to reveal answer
What does np.random.default_rng() return?
AA random integer
BA random float between 0 and 1
CA new random number generator object
DA global random seed
How do you generate 10 random floats between 0 and 1 using default_rng()?
Arng.integers(0, 1, size=10)
Brng.uniform(0, 1)
Cnp.random.rand(10)
Drng.random(10)
Why should you use default_rng() instead of np.random.rand()?
AIt is slower but more compatible
BIt provides better randomness and control
CIt uses global state
DIt does not support seeding
How do you make random results repeatable with default_rng()?
AUse <code>rng = np.random.default_rng(seed=123)</code>
BUse <code>rng = np.random.default_rng()</code> without arguments
CCall <code>rng.seed(123)</code> after creation
DSet a global seed with <code>np.random.seed(123)</code>
Which method generates random integers with default_rng()?
Arng.integers()
Brng.random()
Crng.randint()
Drng.uniform()
Explain how to create a random number generator with a fixed seed using np.random.default_rng() and generate 3 random floats.
Think about how to pass a seed and call the method for floats.
You got /3 concepts.
    Describe the advantages of using np.random.default_rng() over older NumPy random functions.
    Focus on quality, control, and best practice.
    You got /4 concepts.