Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Farama Foundation Gymnasium Np Random

From Leeroopedia
Knowledge Sources
Domains Reinforcement_Learning, Random_Number_Generation
Last Updated 2026-02-15 03:00 GMT

Overview

Provides the np_random seeding function that creates reproducible NumPy random number generators for Gymnasium environments.

Description

The seeding module provides the core random number generation infrastructure for Gymnasium environments. Its primary function, np_random, creates a numpy.random.Generator instance backed by the PCG64 bit generator, seeded via NumPy's SeedSequence.

When called with seed=None, the function generates a random seed (using system entropy via SeedSequence) and returns both the generator and the seed that was used, enabling reproducibility even from random initialization. When called with an explicit integer seed, it validates that the seed is a non-negative integer and raises a gymnasium.error.Error otherwise.

The module also defines the type aliases RNG and RandomNumberGenerator, both of which are set to np.random.Generator, for use in type annotations throughout the codebase.

This function is called internally by Env.reset(seed=...) to initialize or reseed an environment's random number generator.

Usage

Use np_random when implementing custom environments that need a reproducible random number generator. Call it in the reset() method with the provided seed to initialize self.np_random.

Code Reference

Source Location

Signature

def np_random(seed: int | None = None) -> tuple[np.random.Generator, int]

RNG = RandomNumberGenerator = np.random.Generator

Import

from gymnasium.utils.seeding import np_random
# or
from gymnasium.utils import seeding
rng, seed = seeding.np_random(42)

I/O Contract

Inputs

Name Type Required Description
seed int or None No Non-negative integer seed. If None, a random seed is generated from system entropy.

Outputs

Name Type Description
rng np.random.Generator A NumPy random number generator (PCG64-backed)
seed int The seed used to create the generator (useful when input seed was None)

Usage Examples

from gymnasium.utils.seeding import np_random

# Deterministic seeding
rng, seed = np_random(42)
print(f"Seed used: {seed}")
print(f"Random value: {rng.random()}")

# Random seeding (returns the generated seed)
rng, seed = np_random(None)
print(f"Auto-generated seed: {seed}")

# Use in a custom environment
class MyEnv:
    def reset(self, seed=None):
        self.np_random, self._seed = np_random(seed)
        return self.np_random.random(), {}

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment