or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-creation.mdcuda-management.mdfft.mdindex.mdkernels.mdlinear-algebra.mdmath-functions.mdrandom.mdscipy-extensions.mdsparse.mdstatistics.md

random.mddocs/

0

# Random Number Generation

1

2

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.

3

4

## Capabilities

5

6

### Simple Random Data

7

8

Basic random number generation functions with NumPy-compatible interface.

9

10

```python { .api }

11

def rand(*args):

12

"""

13

Random values in [0, 1) from uniform distribution.

14

15

Parameters:

16

- args: ints, dimensions of output array

17

18

Returns:

19

cupy.ndarray: Random values with shape (*args,)

20

"""

21

22

def randn(*args):

23

"""

24

Random values from standard normal distribution.

25

26

Parameters:

27

- args: ints, dimensions of output array

28

29

Returns:

30

cupy.ndarray: Standard normal random values

31

"""

32

33

def randint(low, high=None, size=None, dtype=int):

34

"""

35

Random integers from discrete uniform distribution.

36

37

Parameters:

38

- low: int, lowest (signed) integer to draw

39

- high: int or None, highest (signed) integer to draw (exclusive)

40

- size: int or tuple of ints, output shape

41

- dtype: data type, integer type of output

42

43

Returns:

44

cupy.ndarray: Random integers

45

"""

46

47

def random_sample(size=None):

48

"""

49

Random floats in [0.0, 1.0).

50

51

Parameters:

52

- size: int or tuple of ints, output shape

53

54

Returns:

55

cupy.ndarray: Random floats

56

"""

57

58

def random(size=None):

59

"""Random floats in [0.0, 1.0) (alias for random_sample)."""

60

61

def ranf(size=None):

62

"""Random floats in [0.0, 1.0) (alias for random_sample)."""

63

64

def sample(size=None):

65

"""Random floats in [0.0, 1.0) (alias for random_sample)."""

66

```

67

68

### Legacy Random State Management

69

70

NumPy-compatible random state management for reproducible results.

71

72

```python { .api }

73

def seed(seed=None):

74

"""

75

Seed the legacy random number generator.

76

77

Parameters:

78

- seed: int or None, random seed

79

"""

80

81

def get_random_state():

82

"""

83

Get current RandomState instance.

84

85

Returns:

86

RandomState: Current random state

87

"""

88

89

def set_random_state(state):

90

"""

91

Set RandomState instance.

92

93

Parameters:

94

- state: RandomState, random state to use

95

"""

96

97

def reset_states():

98

"""Reset random number generator states."""

99

100

class RandomState:

101

"""

102

Legacy random number generator (NumPy compatible).

103

104

Parameters:

105

- seed: int or None, random seed

106

"""

107

def __init__(self, seed=None): ...

108

109

def seed(self, seed=None): ...

110

def get_state(self): ...

111

def set_state(self, state): ...

112

113

# All distribution methods available

114

def rand(self, *args): ...

115

def randn(self, *args): ...

116

def randint(self, low, high=None, size=None, dtype=int): ...

117

def random_sample(self, size=None): ...

118

# ... (all distribution methods)

119

```

120

121

### Modern Generator API

122

123

High-performance random number generation with improved statistical quality.

124

125

```python { .api }

126

def default_rng(seed=None):

127

"""

128

Construct new Generator with default BitGenerator (XORWOW).

129

130

Parameters:

131

- seed: int, array-like, SeedSequence, BitGenerator, Generator, or None

132

Seed for initializing the BitGenerator

133

134

Returns:

135

Generator: Initialized random number generator

136

"""

137

138

class Generator:

139

"""

140

Modern random number generator with pluggable BitGenerators.

141

142

Parameters:

143

- bit_generator: BitGenerator, underlying bit generator

144

"""

145

def __init__(self, bit_generator): ...

146

147

@property

148

def bit_generator(self): ...

149

150

def random(self, size=None, dtype=float64, out=None):

151

"""

152

Random floats in [0.0, 1.0).

153

154

Parameters:

155

- size: int or tuple of ints, output shape

156

- dtype: data type, float type of output

157

- out: cupy.ndarray, output array

158

159

Returns:

160

cupy.ndarray: Random floats

161

"""

162

163

def integers(self, low, high=None, size=None, dtype=int64, endpoint=False):

164

"""

165

Random integers from discrete uniform distribution.

166

167

Parameters:

168

- low: int, lowest integer to draw

169

- high: int or None, highest integer to draw

170

- size: int or tuple of ints, output shape

171

- dtype: data type, integer type of output

172

- endpoint: bool, whether to include high value

173

174

Returns:

175

cupy.ndarray: Random integers

176

"""

177

178

def standard_normal(self, size=None, dtype=float64, out=None):

179

"""Random values from standard normal distribution."""

180

181

def normal(self, loc=0.0, scale=1.0, size=None):

182

"""Random values from normal distribution."""

183

184

def uniform(self, low=0.0, high=1.0, size=None):

185

"""Random values from uniform distribution."""

186

187

# Additional distribution methods...

188

```

189

190

### Bit Generators

191

192

Low-level random bit generators providing the foundation for random number generation.

193

194

```python { .api }

195

class BitGenerator:

196

"""Base class for bit generators."""

197

@property

198

def state(self): ...

199

@state.setter

200

def state(self, value): ...

201

202

class XORWOW:

203

"""

204

XORWOW bit generator (default, fast).

205

206

Parameters:

207

- seed: int or None, random seed

208

"""

209

def __init__(self, seed=None): ...

210

211

class MRG32k3a:

212

"""

213

MRG32k3a bit generator (high quality, slower).

214

215

Parameters:

216

- seed: int or None, random seed

217

"""

218

def __init__(self, seed=None): ...

219

220

class Philox4x3210:

221

"""

222

Philox 4x32 bit generator (counter-based).

223

224

Parameters:

225

- seed: int or None, random seed

226

"""

227

def __init__(self, seed=None): ...

228

```

229

230

### Probability Distributions

231

232

Comprehensive set of probability distributions for statistical sampling.

233

234

```python { .api }

235

def uniform(low=0.0, high=1.0, size=None):

236

"""

237

Random values from uniform distribution.

238

239

Parameters:

240

- low: float, lower boundary of output interval

241

- high: float, upper boundary of output interval

242

- size: int or tuple of ints, output shape

243

244

Returns:

245

cupy.ndarray: Uniform random values in [low, high)

246

"""

247

248

def normal(loc=0.0, scale=1.0, size=None):

249

"""

250

Random values from normal (Gaussian) distribution.

251

252

Parameters:

253

- loc: float, mean of distribution

254

- scale: float, standard deviation

255

- size: int or tuple of ints, output shape

256

257

Returns:

258

cupy.ndarray: Normal random values

259

"""

260

261

def standard_normal(size=None):

262

"""Random values from standard normal distribution (mean=0, std=1)."""

263

264

def exponential(scale=1.0, size=None):

265

"""

266

Random values from exponential distribution.

267

268

Parameters:

269

- scale: float, scale parameter (1/rate)

270

- size: int or tuple of ints, output shape

271

272

Returns:

273

cupy.ndarray: Exponential random values

274

"""

275

276

def gamma(shape, scale=1.0, size=None):

277

"""

278

Random values from gamma distribution.

279

280

Parameters:

281

- shape: float, shape parameter

282

- scale: float, scale parameter

283

- size: int or tuple of ints, output shape

284

285

Returns:

286

cupy.ndarray: Gamma random values

287

"""

288

289

def beta(a, b, size=None):

290

"""

291

Random values from beta distribution.

292

293

Parameters:

294

- a: float, alpha parameter

295

- b: float, beta parameter

296

- size: int or tuple of ints, output shape

297

298

Returns:

299

cupy.ndarray: Beta random values in [0, 1]

300

"""

301

302

def binomial(n, p, size=None):

303

"""

304

Random values from binomial distribution.

305

306

Parameters:

307

- n: int, number of trials

308

- p: float, probability of success

309

- size: int or tuple of ints, output shape

310

311

Returns:

312

cupy.ndarray: Binomial random values

313

"""

314

315

def poisson(lam=1.0, size=None):

316

"""

317

Random values from Poisson distribution.

318

319

Parameters:

320

- lam: float, expected number of events

321

- size: int or tuple of ints, output shape

322

323

Returns:

324

cupy.ndarray: Poisson random values

325

"""

326

327

def chisquare(df, size=None):

328

"""

329

Random values from chi-square distribution.

330

331

Parameters:

332

- df: float, degrees of freedom

333

- size: int or tuple of ints, output shape

334

335

Returns:

336

cupy.ndarray: Chi-square random values

337

"""

338

339

def laplace(loc=0.0, scale=1.0, size=None):

340

"""Random values from Laplace distribution."""

341

342

def logistic(loc=0.0, scale=1.0, size=None):

343

"""Random values from logistic distribution."""

344

345

def lognormal(mean=0.0, sigma=1.0, size=None):

346

"""Random values from log-normal distribution."""

347

348

def geometric(p, size=None):

349

"""Random values from geometric distribution."""

350

351

def hypergeometric(ngood, nbad, nsample, size=None):

352

"""

353

Random values from hypergeometric distribution.

354

355

Parameters:

356

- ngood: int, number of success states in population

357

- nbad: int, number of failure states in population

358

- nsample: int, number of items sampled

359

- size: int or tuple of ints, output shape

360

361

Returns:

362

cupy.ndarray: Hypergeometric random values

363

"""

364

```

365

366

### Multivariate Distributions

367

368

Distributions for generating correlated random variables.

369

370

```python { .api }

371

def multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8):

372

"""

373

Random values from multivariate normal distribution.

374

375

Parameters:

376

- mean: array-like, mean vector

377

- cov: array-like, covariance matrix

378

- size: int or tuple of ints, number of samples

379

- check_valid: {'warn', 'raise', 'ignore'}, covariance validation

380

- tol: float, tolerance for singular values

381

382

Returns:

383

cupy.ndarray: Multivariate normal samples

384

"""

385

386

def dirichlet(alpha, size=None):

387

"""

388

Random values from Dirichlet distribution.

389

390

Parameters:

391

- alpha: array-like, concentration parameters

392

- size: int or tuple of ints, output shape

393

394

Returns:

395

cupy.ndarray: Dirichlet random values (sum to 1)

396

"""

397

398

def multinomial(n, pvals, size=None):

399

"""

400

Random values from multinomial distribution.

401

402

Parameters:

403

- n: int, number of trials

404

- pvals: array-like, probabilities (must sum to 1)

405

- size: int or tuple of ints, output shape

406

407

Returns:

408

cupy.ndarray: Multinomial random values

409

"""

410

```

411

412

### Permutations and Sampling

413

414

Functions for shuffling and sampling arrays.

415

416

```python { .api }

417

def shuffle(x):

418

"""

419

Modify sequence in-place by shuffling its contents.

420

421

Parameters:

422

- x: cupy.ndarray, array to shuffle (modified in-place)

423

"""

424

425

def permutation(x):

426

"""

427

Return random permutation of sequence or range.

428

429

Parameters:

430

- x: int or array-like, if int, permute range(x)

431

432

Returns:

433

cupy.ndarray: Permuted array

434

"""

435

436

def choice(a, size=None, replace=True, p=None):

437

"""

438

Generate random sample from array.

439

440

Parameters:

441

- a: int or array-like, if int, sample from range(a)

442

- size: int or tuple of ints, output shape

443

- replace: bool, whether to sample with replacement

444

- p: array-like or None, probabilities for each element

445

446

Returns:

447

cupy.ndarray: Random sample

448

"""

449

```

450

451

### Additional Distributions

452

453

Extended set of probability distributions.

454

455

```python { .api }

456

def triangular(left, mode, right, size=None):

457

"""Random values from triangular distribution."""

458

459

def weibull(a, size=None):

460

"""Random values from Weibull distribution."""

461

462

def pareto(a, size=None):

463

"""Random values from Pareto distribution."""

464

465

def power(a, size=None):

466

"""Random values from power distribution."""

467

468

def rayleigh(scale=1.0, size=None):

469

"""Random values from Rayleigh distribution."""

470

471

def vonmises(mu, kappa, size=None):

472

"""Random values from von Mises distribution."""

473

474

def wald(mean, scale, size=None):

475

"""Random values from Wald (inverse Gaussian) distribution."""

476

477

def zipf(a, size=None):

478

"""Random values from Zipf distribution."""

479

480

def f(dfnum, dfden, size=None):

481

"""Random values from F distribution."""

482

483

def gumbel(loc=0.0, scale=1.0, size=None):

484

"""Random values from Gumbel distribution."""

485

486

def logseries(p, size=None):

487

"""Random values from logarithmic series distribution."""

488

489

def negative_binomial(n, p, size=None):

490

"""Random values from negative binomial distribution."""

491

492

def noncentral_chisquare(df, nonc, size=None):

493

"""Random values from noncentral chi-square distribution."""

494

495

def noncentral_f(dfnum, dfden, nonc, size=None):

496

"""Random values from noncentral F distribution."""

497

498

def standard_cauchy(size=None):

499

"""Random values from standard Cauchy distribution."""

500

501

def standard_exponential(size=None):

502

"""Random values from standard exponential distribution."""

503

504

def standard_gamma(shape, size=None):

505

"""Random values from standard gamma distribution."""

506

507

def standard_t(df, size=None):

508

"""Random values from Student's t distribution."""

509

```

510

511

## Usage Examples

512

513

### Basic Random Number Generation

514

515

```python

516

import cupy as cp

517

518

# Simple random arrays

519

random_uniform = cp.random.rand(1000, 1000) # Uniform [0,1)

520

random_normal = cp.random.randn(1000, 1000) # Standard normal

521

random_ints = cp.random.randint(0, 100, size=(1000,)) # Integers [0,100)

522

523

# Specific distributions

524

exponential_data = cp.random.exponential(scale=2.0, size=(10000,))

525

gamma_data = cp.random.gamma(shape=2.0, scale=1.0, size=(10000,))

526

```

527

528

### Modern Generator API

529

530

```python

531

# Create generator with specific seed for reproducibility

532

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

533

534

# Generate high-quality random numbers

535

uniform_samples = rng.random(size=(1000, 1000))

536

normal_samples = rng.standard_normal(size=(1000, 1000))

537

integers = rng.integers(low=0, high=100, size=(1000,))

538

539

# Different bit generators for specific needs

540

philox_rng = cp.random.Generator(cp.random.Philox4x3210(seed=123))

541

high_quality_samples = philox_rng.random(size=(10000,))

542

```

543

544

### Statistical Sampling and Analysis

545

546

```python

547

# Multivariate normal distribution

548

mean = cp.array([0, 0])

549

cov = cp.array([[1, 0.5], [0.5, 1]])

550

mvn_samples = cp.random.multivariate_normal(mean, cov, size=10000)

551

552

# Binomial experiments

553

success_counts = cp.random.binomial(n=100, p=0.3, size=10000)

554

success_rate = cp.mean(success_counts) / 100

555

556

# Sampling from custom distributions

557

# Sample from discrete distribution

558

probs = cp.array([0.1, 0.2, 0.3, 0.4])

559

samples = cp.random.choice(4, size=10000, p=probs)

560

```

561

562

### Permutations and Shuffling

563

564

```python

565

# Shuffle arrays in-place

566

data = cp.arange(1000)

567

cp.random.shuffle(data) # data is now shuffled

568

569

# Random permutations (creates copy)

570

original = cp.arange(100)

571

permuted = cp.random.permutation(original)

572

573

# Bootstrap sampling

574

bootstrap_indices = cp.random.choice(len(data), size=len(data), replace=True)

575

bootstrap_sample = data[bootstrap_indices]

576

577

# Sample without replacement

578

subsample_indices = cp.random.choice(len(data), size=100, replace=False)

579

subsample = data[subsample_indices]

580

```

581

582

### Reproducible Random Number Generation

583

584

```python

585

# Set global seed for reproducibility

586

cp.random.seed(42)

587

arr1 = cp.random.random((100, 100))

588

589

cp.random.seed(42) # Reset to same seed

590

arr2 = cp.random.random((100, 100))

591

# arr1 and arr2 are identical

592

593

# Use RandomState for independent streams

594

rs1 = cp.random.RandomState(seed=123)

595

rs2 = cp.random.RandomState(seed=456)

596

597

stream1_data = rs1.normal(size=(1000,))

598

stream2_data = rs2.normal(size=(1000,))

599

# Independent random streams

600

601

# Modern approach with Generator

602

rng = cp.random.default_rng(seed=789)

603

reproducible_data = rng.standard_normal(size=(1000, 1000))

604

```

605

606

### Performance Optimization

607

608

```python

609

# Pre-allocate output arrays for better performance

610

output = cp.empty((10000, 10000), dtype=cp.float32)

611

cp.random.rand(*output.shape, dtype=cp.float32, out=output)

612

613

# Batch generation for large datasets

614

batch_size = 1000000

615

total_samples = 100000000

616

617

results = []

618

for i in range(0, total_samples, batch_size):

619

batch = cp.random.normal(size=min(batch_size, total_samples - i))

620

results.append(batch)

621

622

all_samples = cp.concatenate(results)

623

```