NumPy & SciPy for GPU - CUDA 11.0 compatible package providing GPU-accelerated computing with Python through a NumPy/SciPy-compatible array library
—
GPU-accelerated random number generation supporting various probability distributions and random sampling operations. Provides high-performance random number generation using cuRAND library for statistical simulations and Monte Carlo methods.
Core random number generation functions for common distributions.
def random(size=None, dtype=float):
"""
Random values in half-open interval [0.0, 1.0).
Parameters:
- size: int/tuple, output shape
- dtype: data type of output
Returns:
cupy.ndarray: Random values from uniform distribution
"""
def rand(*args):
"""Random values in half-open interval [0.0, 1.0) with given shape."""
def randn(*args):
"""Random values from standard normal distribution."""
def randint(low, high=None, size=None, dtype=int):
"""
Random integers from low (inclusive) to high (exclusive).
Parameters:
- low: int, lowest integer to draw
- high: int, highest integer to draw (exclusive)
- size: int/tuple, output shape
- dtype: data type of output
Returns:
cupy.ndarray: Random integers
"""
def seed(seed=None):
"""Seed the random number generator."""
def get_random_state():
"""Get current random state."""
def set_random_state(state):
"""Set random state."""Random sampling from uniform distributions over various intervals.
def uniform(low=0.0, high=1.0, size=None):
"""
Draw samples from uniform distribution.
Parameters:
- low: float, lower boundary of output interval
- high: float, upper boundary of output interval
- size: int/tuple, output shape
Returns:
cupy.ndarray: Random samples from uniform distribution
"""
def random_sample(size=None):
"""Random floats in half-open interval [0.0, 1.0)."""
def sample(size=None):
"""Alias for random_sample."""
def random_integers(low, high=None, size=None):
"""Random integers between low and high, inclusive."""Gaussian and related continuous probability distributions.
def normal(loc=0.0, scale=1.0, size=None):
"""
Draw samples from normal (Gaussian) distribution.
Parameters:
- loc: float, mean of distribution
- scale: float, standard deviation
- size: int/tuple, output shape
Returns:
cupy.ndarray: Random samples from normal distribution
"""
def standard_normal(size=None):
"""Draw samples from standard normal distribution (mean=0, std=1)."""
def lognormal(mean=0.0, sigma=1.0, size=None):
"""Draw samples from log-normal distribution."""
def multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8):
"""
Draw samples from multivariate normal distribution.
Parameters:
- mean: array_like, mean of distribution
- cov: array_like, covariance matrix
- size: int/tuple, shape of output
- check_valid: str, behavior for non-positive-semidefinite covariance
- tol: float, tolerance for covariance matrix validation
Returns:
cupy.ndarray: Random samples from multivariate normal
"""Random sampling from discrete probability distributions.
def binomial(n, p, size=None):
"""
Draw samples from binomial distribution.
Parameters:
- n: int, number of trials
- p: float, probability of success in each trial
- size: int/tuple, output shape
Returns:
cupy.ndarray: Random samples from binomial distribution
"""
def poisson(lam=1.0, size=None):
"""Draw samples from Poisson distribution."""
def geometric(p, size=None):
"""Draw samples from geometric distribution."""
def negative_binomial(n, p, size=None):
"""Draw samples from negative binomial distribution."""
def hypergeometric(ngood, nbad, nsample, size=None):
"""Draw samples from hypergeometric distribution."""Various continuous probability distributions for statistical modeling.
def exponential(scale=1.0, size=None):
"""
Draw samples from exponential distribution.
Parameters:
- scale: float, scale parameter (1/rate)
- size: int/tuple, output shape
Returns:
cupy.ndarray: Random samples from exponential distribution
"""
def gamma(shape, scale=1.0, size=None):
"""Draw samples from Gamma distribution."""
def beta(a, b, size=None):
"""Draw samples from Beta distribution."""
def chisquare(df, size=None):
"""Draw samples from chi-square distribution."""
def f(dfnum, dfden, size=None):
"""Draw samples from F distribution."""
def weibull(a, size=None):
"""Draw samples from Weibull distribution."""
def laplace(loc=0.0, scale=1.0, size=None):
"""Draw samples from Laplace distribution."""
def logistic(loc=0.0, scale=1.0, size=None):
"""Draw samples from logistic distribution."""
def gumbel(loc=0.0, scale=1.0, size=None):
"""Draw samples from Gumbel distribution."""
def pareto(a, size=None):
"""Draw samples from Pareto II distribution."""
def power(a, size=None):
"""Draw samples from power distribution."""
def rayleigh(scale=1.0, size=None):
"""Draw samples from Rayleigh distribution."""
def standard_cauchy(size=None):
"""Draw samples from standard Cauchy distribution."""
def standard_exponential(size=None):
"""Draw samples from standard exponential distribution."""
def standard_gamma(shape, size=None):
"""Draw samples from standard Gamma distribution."""
def standard_t(df, size=None):
"""Draw samples from Student's t-distribution."""
def triangular(left, mode, right, size=None):
"""Draw samples from triangular distribution."""
def vonmises(mu, kappa, size=None):
"""Draw samples from von Mises distribution."""
def wald(mean, scale, size=None):
"""Draw samples from Wald (inverse Gaussian) distribution."""
def zipf(a, size=None):
"""Draw samples from Zipf distribution."""Functions for random sampling and selection from existing data.
def choice(a, size=None, replace=True, p=None):
"""
Generate random sample from given 1-D array.
Parameters:
- a: array_like/int, input array or integer (range)
- size: int/tuple, output shape
- replace: bool, whether sample is with/without replacement
- p: array_like, probabilities associated with each entry
Returns:
cupy.ndarray: Random samples from input array
"""
def shuffle(x):
"""Modify sequence in-place by shuffling its contents."""
def permutation(x):
"""Randomly permute sequence or return permuted range."""Control and management of random number generator state.
class RandomState:
"""
Container for random number generator state.
Parameters:
- seed: int, seed for random number generator
"""
def __init__(self, seed=None): ...
def seed(self, seed=None):
"""Seed random number generator."""
def get_state(self):
"""Return tuple representing internal state."""
def set_state(self, state):
"""Set internal state from tuple."""
# Distribution methods (same as module-level functions)
def random(self, size=None, dtype=float): ...
def normal(self, loc=0.0, scale=1.0, size=None): ...
def uniform(self, low=0.0, high=1.0, size=None): ...
# ... all other distribution methodsimport cupy as cp
# Set seed for reproducibility
cp.random.seed(42)
# Generate uniform random numbers
uniform_data = cp.random.random((1000, 1000))
uniform_range = cp.random.uniform(-1, 1, (500, 500))
# Generate normal random numbers
normal_data = cp.random.normal(0, 1, (1000, 1000))
custom_normal = cp.random.normal(10, 2.5, (100, 100))
# Generate random integers
random_ints = cp.random.randint(0, 100, (50, 50))
dice_rolls = cp.random.randint(1, 7, 1000)# Exponential distribution (modeling waiting times)
waiting_times = cp.random.exponential(2.0, 10000)
# Gamma distribution (modeling continuous positive values)
gamma_samples = cp.random.gamma(2, 2, 5000)
# Beta distribution (modeling proportions)
proportions = cp.random.beta(2, 5, 1000)
# Poisson distribution (modeling count data)
event_counts = cp.random.poisson(3.5, 10000)
# Binomial distribution (modeling success/failure trials)
successes = cp.random.binomial(100, 0.3, 5000)# 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, 1000)
# Multiple correlated variables
n_vars = 5
mean = cp.zeros(n_vars)
correlation = 0.3
cov = correlation * cp.ones((n_vars, n_vars))
cp.fill_diagonal(cov, 1.0)
correlated_data = cp.random.multivariate_normal(mean, cov, 10000)# Random choice from array
data = cp.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
random_samples = cp.random.choice(data, size=100, replace=True)
# Weighted random sampling
weights = cp.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
weighted_samples = cp.random.choice(data, size=100, p=weights)
# Random permutation
permuted_data = cp.random.permutation(data)
# Shuffle in place
cp.random.shuffle(data) # Modifies data array# Estimate π using Monte Carlo method
n_samples = 1000000
x = cp.random.uniform(-1, 1, n_samples)
y = cp.random.uniform(-1, 1, n_samples)
inside_circle = (x**2 + y**2) <= 1
pi_estimate = 4 * cp.mean(inside_circle)
# Random walk simulation
n_steps = 10000
steps = cp.random.choice([-1, 1], size=n_steps)
position = cp.cumsum(steps)
# Portfolio simulation
n_assets = 10
n_scenarios = 100000
returns = cp.random.multivariate_normal(
mean=cp.full(n_assets, 0.08), # 8% expected return
cov=0.04 * cp.eye(n_assets), # 20% volatility, uncorrelated
size=n_scenarios
)# Create separate random state
rng = cp.random.RandomState(12345)
# Generate samples with specific state
samples1 = rng.normal(0, 1, 1000)
samples2 = rng.uniform(0, 1, 1000)
# Save and restore state
state = rng.get_state()
more_samples = rng.normal(0, 1, 1000)
# Restore previous state
rng.set_state(state)
repeated_samples = rng.normal(0, 1, 1000) # Same as more_samples
# Multiple independent generators
rng1 = cp.random.RandomState(111)
rng2 = cp.random.RandomState(222)
# Generate independent sequences
seq1 = rng1.random(1000)
seq2 = rng2.random(1000)# Generate autoregressive time series
n_points = 10000
phi = 0.7 # Autoregressive parameter
noise = cp.random.normal(0, 1, n_points)
ar_series = cp.zeros(n_points)
for i in range(1, n_points):
ar_series[i] = phi * ar_series[i-1] + noise[i]
# Generate random walk with drift
drift = 0.01
innovations = cp.random.normal(drift, 0.1, n_points)
random_walk = cp.cumsum(innovations)
# Geometric Brownian motion (stock price model)
S0 = 100 # Initial price
mu = 0.1 # Drift
sigma = 0.2 # Volatility
dt = 1/252 # Daily time step
dW = cp.random.normal(0, cp.sqrt(dt), n_points)
log_returns = (mu - 0.5*sigma**2)*dt + sigma*dW
stock_prices = S0 * cp.exp(cp.cumsum(log_returns))Install with Tessl CLI
npx tessl i tessl/pypi-cupy-cuda110