NumPy & SciPy-compatible array library for GPU-accelerated computing with Python
—
GPU-accelerated random number generation with multiple generators and probability distributions. CuPy provides both a legacy NumPy-compatible interface and a modern Generator API with improved performance and statistical quality.
Basic random number generation functions with NumPy-compatible interface.
def rand(*args):
"""
Random values in [0, 1) from uniform distribution.
Parameters:
- args: ints, dimensions of output array
Returns:
cupy.ndarray: Random values with shape (*args,)
"""
def randn(*args):
"""
Random values from standard normal distribution.
Parameters:
- args: ints, dimensions of output array
Returns:
cupy.ndarray: Standard normal random values
"""
def randint(low, high=None, size=None, dtype=int):
"""
Random integers from discrete uniform distribution.
Parameters:
- low: int, lowest (signed) integer to draw
- high: int or None, highest (signed) integer to draw (exclusive)
- size: int or tuple of ints, output shape
- dtype: data type, integer type of output
Returns:
cupy.ndarray: Random integers
"""
def random_sample(size=None):
"""
Random floats in [0.0, 1.0).
Parameters:
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Random floats
"""
def random(size=None):
"""Random floats in [0.0, 1.0) (alias for random_sample)."""
def ranf(size=None):
"""Random floats in [0.0, 1.0) (alias for random_sample)."""
def sample(size=None):
"""Random floats in [0.0, 1.0) (alias for random_sample)."""NumPy-compatible random state management for reproducible results.
def seed(seed=None):
"""
Seed the legacy random number generator.
Parameters:
- seed: int or None, random seed
"""
def get_random_state():
"""
Get current RandomState instance.
Returns:
RandomState: Current random state
"""
def set_random_state(state):
"""
Set RandomState instance.
Parameters:
- state: RandomState, random state to use
"""
def reset_states():
"""Reset random number generator states."""
class RandomState:
"""
Legacy random number generator (NumPy compatible).
Parameters:
- seed: int or None, random seed
"""
def __init__(self, seed=None): ...
def seed(self, seed=None): ...
def get_state(self): ...
def set_state(self, state): ...
# All distribution methods available
def rand(self, *args): ...
def randn(self, *args): ...
def randint(self, low, high=None, size=None, dtype=int): ...
def random_sample(self, size=None): ...
# ... (all distribution methods)High-performance random number generation with improved statistical quality.
def default_rng(seed=None):
"""
Construct new Generator with default BitGenerator (XORWOW).
Parameters:
- seed: int, array-like, SeedSequence, BitGenerator, Generator, or None
Seed for initializing the BitGenerator
Returns:
Generator: Initialized random number generator
"""
class Generator:
"""
Modern random number generator with pluggable BitGenerators.
Parameters:
- bit_generator: BitGenerator, underlying bit generator
"""
def __init__(self, bit_generator): ...
@property
def bit_generator(self): ...
def random(self, size=None, dtype=float64, out=None):
"""
Random floats in [0.0, 1.0).
Parameters:
- size: int or tuple of ints, output shape
- dtype: data type, float type of output
- out: cupy.ndarray, output array
Returns:
cupy.ndarray: Random floats
"""
def integers(self, low, high=None, size=None, dtype=int64, endpoint=False):
"""
Random integers from discrete uniform distribution.
Parameters:
- low: int, lowest integer to draw
- high: int or None, highest integer to draw
- size: int or tuple of ints, output shape
- dtype: data type, integer type of output
- endpoint: bool, whether to include high value
Returns:
cupy.ndarray: Random integers
"""
def standard_normal(self, size=None, dtype=float64, out=None):
"""Random values from standard normal distribution."""
def normal(self, loc=0.0, scale=1.0, size=None):
"""Random values from normal distribution."""
def uniform(self, low=0.0, high=1.0, size=None):
"""Random values from uniform distribution."""
# Additional distribution methods...Low-level random bit generators providing the foundation for random number generation.
class BitGenerator:
"""Base class for bit generators."""
@property
def state(self): ...
@state.setter
def state(self, value): ...
class XORWOW:
"""
XORWOW bit generator (default, fast).
Parameters:
- seed: int or None, random seed
"""
def __init__(self, seed=None): ...
class MRG32k3a:
"""
MRG32k3a bit generator (high quality, slower).
Parameters:
- seed: int or None, random seed
"""
def __init__(self, seed=None): ...
class Philox4x3210:
"""
Philox 4x32 bit generator (counter-based).
Parameters:
- seed: int or None, random seed
"""
def __init__(self, seed=None): ...Comprehensive set of probability distributions for statistical sampling.
def uniform(low=0.0, high=1.0, size=None):
"""
Random values from uniform distribution.
Parameters:
- low: float, lower boundary of output interval
- high: float, upper boundary of output interval
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Uniform random values in [low, high)
"""
def normal(loc=0.0, scale=1.0, size=None):
"""
Random values from normal (Gaussian) distribution.
Parameters:
- loc: float, mean of distribution
- scale: float, standard deviation
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Normal random values
"""
def standard_normal(size=None):
"""Random values from standard normal distribution (mean=0, std=1)."""
def exponential(scale=1.0, size=None):
"""
Random values from exponential distribution.
Parameters:
- scale: float, scale parameter (1/rate)
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Exponential random values
"""
def gamma(shape, scale=1.0, size=None):
"""
Random values from gamma distribution.
Parameters:
- shape: float, shape parameter
- scale: float, scale parameter
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Gamma random values
"""
def beta(a, b, size=None):
"""
Random values from beta distribution.
Parameters:
- a: float, alpha parameter
- b: float, beta parameter
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Beta random values in [0, 1]
"""
def binomial(n, p, size=None):
"""
Random values from binomial distribution.
Parameters:
- n: int, number of trials
- p: float, probability of success
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Binomial random values
"""
def poisson(lam=1.0, size=None):
"""
Random values from Poisson distribution.
Parameters:
- lam: float, expected number of events
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Poisson random values
"""
def chisquare(df, size=None):
"""
Random values from chi-square distribution.
Parameters:
- df: float, degrees of freedom
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Chi-square random values
"""
def laplace(loc=0.0, scale=1.0, size=None):
"""Random values from Laplace distribution."""
def logistic(loc=0.0, scale=1.0, size=None):
"""Random values from logistic distribution."""
def lognormal(mean=0.0, sigma=1.0, size=None):
"""Random values from log-normal distribution."""
def geometric(p, size=None):
"""Random values from geometric distribution."""
def hypergeometric(ngood, nbad, nsample, size=None):
"""
Random values from hypergeometric distribution.
Parameters:
- ngood: int, number of success states in population
- nbad: int, number of failure states in population
- nsample: int, number of items sampled
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Hypergeometric random values
"""Distributions for generating correlated random variables.
def multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8):
"""
Random values from multivariate normal distribution.
Parameters:
- mean: array-like, mean vector
- cov: array-like, covariance matrix
- size: int or tuple of ints, number of samples
- check_valid: {'warn', 'raise', 'ignore'}, covariance validation
- tol: float, tolerance for singular values
Returns:
cupy.ndarray: Multivariate normal samples
"""
def dirichlet(alpha, size=None):
"""
Random values from Dirichlet distribution.
Parameters:
- alpha: array-like, concentration parameters
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Dirichlet random values (sum to 1)
"""
def multinomial(n, pvals, size=None):
"""
Random values from multinomial distribution.
Parameters:
- n: int, number of trials
- pvals: array-like, probabilities (must sum to 1)
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: Multinomial random values
"""Functions for shuffling and sampling arrays.
def shuffle(x):
"""
Modify sequence in-place by shuffling its contents.
Parameters:
- x: cupy.ndarray, array to shuffle (modified in-place)
"""
def permutation(x):
"""
Return random permutation of sequence or range.
Parameters:
- x: int or array-like, if int, permute range(x)
Returns:
cupy.ndarray: Permuted array
"""
def choice(a, size=None, replace=True, p=None):
"""
Generate random sample from array.
Parameters:
- a: int or array-like, if int, sample from range(a)
- size: int or tuple of ints, output shape
- replace: bool, whether to sample with replacement
- p: array-like or None, probabilities for each element
Returns:
cupy.ndarray: Random sample
"""Extended set of probability distributions.
def triangular(left, mode, right, size=None):
"""Random values from triangular distribution."""
def weibull(a, size=None):
"""Random values from Weibull distribution."""
def pareto(a, size=None):
"""Random values from Pareto distribution."""
def power(a, size=None):
"""Random values from power distribution."""
def rayleigh(scale=1.0, size=None):
"""Random values from Rayleigh distribution."""
def vonmises(mu, kappa, size=None):
"""Random values from von Mises distribution."""
def wald(mean, scale, size=None):
"""Random values from Wald (inverse Gaussian) distribution."""
def zipf(a, size=None):
"""Random values from Zipf distribution."""
def f(dfnum, dfden, size=None):
"""Random values from F distribution."""
def gumbel(loc=0.0, scale=1.0, size=None):
"""Random values from Gumbel distribution."""
def logseries(p, size=None):
"""Random values from logarithmic series distribution."""
def negative_binomial(n, p, size=None):
"""Random values from negative binomial distribution."""
def noncentral_chisquare(df, nonc, size=None):
"""Random values from noncentral chi-square distribution."""
def noncentral_f(dfnum, dfden, nonc, size=None):
"""Random values from noncentral F distribution."""
def standard_cauchy(size=None):
"""Random values from standard Cauchy distribution."""
def standard_exponential(size=None):
"""Random values from standard exponential distribution."""
def standard_gamma(shape, size=None):
"""Random values from standard gamma distribution."""
def standard_t(df, size=None):
"""Random values from Student's t distribution."""import cupy as cp
# Simple random arrays
random_uniform = cp.random.rand(1000, 1000) # Uniform [0,1)
random_normal = cp.random.randn(1000, 1000) # Standard normal
random_ints = cp.random.randint(0, 100, size=(1000,)) # Integers [0,100)
# Specific distributions
exponential_data = cp.random.exponential(scale=2.0, size=(10000,))
gamma_data = cp.random.gamma(shape=2.0, scale=1.0, size=(10000,))# Create generator with specific seed for reproducibility
rng = cp.random.default_rng(seed=42)
# Generate high-quality random numbers
uniform_samples = rng.random(size=(1000, 1000))
normal_samples = rng.standard_normal(size=(1000, 1000))
integers = rng.integers(low=0, high=100, size=(1000,))
# Different bit generators for specific needs
philox_rng = cp.random.Generator(cp.random.Philox4x3210(seed=123))
high_quality_samples = philox_rng.random(size=(10000,))# Multivariate normal distribution
mean = cp.array([0, 0])
cov = cp.array([[1, 0.5], [0.5, 1]])
mvn_samples = cp.random.multivariate_normal(mean, cov, size=10000)
# Binomial experiments
success_counts = cp.random.binomial(n=100, p=0.3, size=10000)
success_rate = cp.mean(success_counts) / 100
# Sampling from custom distributions
# Sample from discrete distribution
probs = cp.array([0.1, 0.2, 0.3, 0.4])
samples = cp.random.choice(4, size=10000, p=probs)# Shuffle arrays in-place
data = cp.arange(1000)
cp.random.shuffle(data) # data is now shuffled
# Random permutations (creates copy)
original = cp.arange(100)
permuted = cp.random.permutation(original)
# Bootstrap sampling
bootstrap_indices = cp.random.choice(len(data), size=len(data), replace=True)
bootstrap_sample = data[bootstrap_indices]
# Sample without replacement
subsample_indices = cp.random.choice(len(data), size=100, replace=False)
subsample = data[subsample_indices]# Set global seed for reproducibility
cp.random.seed(42)
arr1 = cp.random.random((100, 100))
cp.random.seed(42) # Reset to same seed
arr2 = cp.random.random((100, 100))
# arr1 and arr2 are identical
# Use RandomState for independent streams
rs1 = cp.random.RandomState(seed=123)
rs2 = cp.random.RandomState(seed=456)
stream1_data = rs1.normal(size=(1000,))
stream2_data = rs2.normal(size=(1000,))
# Independent random streams
# Modern approach with Generator
rng = cp.random.default_rng(seed=789)
reproducible_data = rng.standard_normal(size=(1000, 1000))# Pre-allocate output arrays for better performance
output = cp.empty((10000, 10000), dtype=cp.float32)
cp.random.rand(*output.shape, dtype=cp.float32, out=output)
# Batch generation for large datasets
batch_size = 1000000
total_samples = 100000000
results = []
for i in range(0, total_samples, batch_size):
batch = cp.random.normal(size=min(batch_size, total_samples - i))
results.append(batch)
all_samples = cp.concatenate(results)Install with Tessl CLI
npx tessl i tessl/pypi-cupy