DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

NumPy Random: Generate Numbers, Ranges, Seeds, and Arrays

Learn when to use NumPy Generator methods for random floats, integer ranges, shaped arrays, reproducible seeds, and parallel streams.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For new Python code, create a NumPy Generator with rng = np.random.default_rng(seed), then call the method that matches the result you need. Use rng.random() for a float in [0.0, 1.0), rng.integers() for integer ranges, and size to choose an array’s dimensions. A seed helps reproduce a run, but NumPy does not guarantee identical Generator output across versions.

Start with NumPy’s Generator

NumPy recommends its modern Generator interface for new random-number code. Create one with np.random.default_rng() and use its methods, rather than relying on the older module-level random functions:

As an Amazon Associate I earn from qualifying purchases.

import numpy as np

rng = np.random.default_rng(seed=42)

# One uniform float in [0.0, 1.0)
u = rng.random()

# Five integers from 0 through 9; 10 is excluded
ids = rng.integers(low=0, high=10, size=5)

# A 3 by 3 array of uniform floats
matrix = rng.random((3, 3))

# 1,000 samples from the standard normal distribution
noise = rng.standard_normal(size=1000)

The default BitGenerator used by default_rng is PCG64. In ordinary use, you can work with the Generator methods without selecting a BitGenerator yourself. See the NumPy random sampling reference and the Generator API reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a method for the value you need

Need Use What it returns
A uniform float rng.random(size=None) A value in [0.0, 1.0), or an array of such values when size is set.
Integers in a range rng.integers(low, high, size=None) Integers from low up to, but not including, high by default.
Normally distributed values rng.standard_normal(size=None) Samples from the standard normal distribution.
Values selected from options rng.choice(...) Random selections from the supplied choices.
A shuffled ordering rng.permutation(...) A permuted sequence or array.

These methods cover common tasks, but the Generator API also includes other distributions and sampling operations. Consult the Generator method reference for the available methods and their arguments.

Understand ranges and the exclusive upper bound

Floats from random()

rng.random() samples from the half-open interval [0.0, 1.0): zero is possible, but one is not. To scale the result to another interval, multiply by its width and add its lower bound. For example, low + (high - low) * rng.random() produces a float in [low, high) when low is less than high.

Integers from integers()

By default, rng.integers(low, high) includes low and excludes high. Thus rng.integers(0, 10) can return 0 through 9, not 10. If you want an inclusive upper bound, pass endpoint=True, for example rng.integers(0, 10, endpoint=True) to allow 0 through 10. Check the interval carefully when using a generated integer as an array index or a count; an exclusive high value is a frequent source of off-by-one errors. The integers reference documents the arguments and endpoint behavior.

Use size to control array shape

For Generator sampling methods that accept size, omit it or leave it as None to get a scalar value. Set it to an integer for a one-dimensional array, or a tuple for a multidimensional shape:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • rng.random() returns one float.
  • rng.random(5) returns a one-dimensional array with five floats.
  • rng.random((2, 3)) returns an array with two rows and three columns.

The same shape idea applies to methods such as integers() and standard_normal(). For example, rng.integers(1, 7, size=(4, 2)) requests a 4-by-2 array of integers from 1 through 6. The random method reference describes the size argument for uniform floats.

Seed a generator to reproduce a run

Pass a seed to default_rng when you need a run to be repeatable:

rng = np.random.default_rng(seed=42)
values = rng.integers(0, 100, size=5)

Reinitializing a generator with the same seed reproduces the same sequence under the same relevant NumPy implementation conditions. This is useful for debugging, examples, and controlled simulations. It is not a promise that the sequence will remain identical across NumPy versions: NumPy explicitly makes no version-compatibility guarantee for the Generator bit stream, which can change as algorithms evolve. Record your NumPy version as well as the seed when reproducibility across environments matters. The Generator documentation explains this compatibility policy.

For applications that need robust seed material rather than a convenient fixed seed, NumPy recommends large positive seed values; its documentation shows obtaining a 128-bit value with Python’s secrets.randbits. A seed is an initialization input, not a security feature.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Create separate random streams for parallel work

When different workers need their own streams, derive them from a shared seed sequence rather than giving every worker the same seed. NumPy provides SeedSequence.spawn and the convenience method Generator.spawn for creating child streams:

import numpy as np

root = np.random.default_rng(2026)
workers = root.spawn(4)

# Each worker gets a separate Generator
worker_values = [worker.random(5) for worker in workers]

NumPy describes spawned streams as independent with very high probability, not as an unconditional mathematical guarantee. If you instead derive worker seeds from a root seed and worker IDs, make those IDs deterministic and unique. Do not initialize every worker with the same small seed. See the NumPy parallel random number generation guide.

Moving from legacy RandomState

RandomState remains available for backward compatibility, so existing code does not vanish when you adopt the newer API. The distinction matters when writing or updating code: use default_rng and Generator for new work, and retain legacy calls only when compatibility with an existing program requires them.

Task Modern API Legacy API
Create a random-number object np.random.default_rng(seed) np.random.RandomState(seed)
Draw integers rng.integers(low, high) randint(low, high)
Recommended for new code Yes No; retained for compatibility
Cross-version stream compatibility Not guaranteed by Generator’s compatibility policy Depends on legacy API behavior and the specific use; do not assume the Generator guarantee applies

The module-level np.random.randint belongs to the legacy interface; its high bound is exclusive too. For new integer draws, use Generator.integers. NumPy’s random reference describes the modern and legacy interfaces.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not use NumPy random for security

NumPy states that its pseudo-random generators are designed for statistical modeling and simulation, and are not suitable for security or cryptographic purposes. Do not use a NumPy generator for passwords, authentication tokens, secret keys, or other security-sensitive values. Python’s secrets module is the appropriate direction for those uses, as noted in NumPy’s random sampling documentation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.