or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-operations.mdcuda-integration.mdfft.mdindex.mdindexing-selection.mdinput-output.mdjit-kernels.mdlinear-algebra.mdlogic-operations.mdmathematical-functions.mdrandom-generation.mdscipy-extensions.mdstatistics.mdtesting.md

random-generation.mddocs/

0

# Random Number Generation

1

2

Comprehensive random number generation capabilities with support for multiple algorithms, distributions, and GPU-accelerated sampling for scientific computing and simulation. CuPy provides GPU-optimized random number generation with compatibility to NumPy's random module.

3

4

## Capabilities

5

6

### Basic Random Functions

7

8

Core random number generation functions for common use cases.

9

10

```python { .api }

11

def random(size=None):

12

"""Random values in [0.0, 1.0) from uniform distribution.

13

14

Args:

15

size: Output shape

16

17

Returns:

18

cupy.ndarray: Random values

19

"""

20

21

def randn(*args):

22

"""Random values from standard normal distribution.

23

24

Args:

25

*args: Output shape dimensions

26

27

Returns:

28

cupy.ndarray: Standard normal random values

29

"""

30

31

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

32

"""Random integers from uniform distribution.

33

34

Args:

35

low: Lowest integer (inclusive)

36

high: Highest integer (exclusive), if None then [0, low)

37

size: Output shape

38

dtype: Output data type

39

40

Returns:

41

cupy.ndarray: Random integers

42

"""

43

44

def rand(*args):

45

"""Random values in [0.0, 1.0) from uniform distribution.

46

47

Args:

48

*args: Output shape dimensions

49

50

Returns:

51

cupy.ndarray: Random values

52

"""

53

54

def seed(seed=None):

55

"""Seed the random number generator.

56

57

Args:

58

seed: Random seed value

59

"""

60

```

61

62

### Probability Distributions

63

64

Generate samples from various probability distributions.

65

66

```python { .api }

67

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

68

"""Normal (Gaussian) distribution samples.

69

70

Args:

71

loc: Mean of distribution

72

scale: Standard deviation

73

size: Output shape

74

75

Returns:

76

cupy.ndarray: Normal distribution samples

77

"""

78

79

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

80

"""Uniform distribution samples.

81

82

Args:

83

low: Lower boundary (inclusive)

84

high: Upper boundary (exclusive)

85

size: Output shape

86

87

Returns:

88

cupy.ndarray: Uniform distribution samples

89

"""

90

91

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

92

"""Exponential distribution samples."""

93

94

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

95

"""Gamma distribution samples."""

96

97

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

98

"""Beta distribution samples."""

99

100

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

101

"""Binomial distribution samples."""

102

103

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

104

"""Poisson distribution samples."""

105

106

def geometric(p, size=None):

107

"""Geometric distribution samples."""

108

109

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

110

"""Negative binomial distribution samples."""

111

112

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

113

"""Hypergeometric distribution samples."""

114

115

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

116

"""Logistic distribution samples."""

117

118

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

119

"""Log-normal distribution samples."""

120

121

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

122

"""Laplace distribution samples."""

123

124

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

125

"""Gumbel distribution samples."""

126

127

def weibull(a, size=None):

128

"""Weibull distribution samples."""

129

130

def pareto(a, size=None):

131

"""Pareto distribution samples."""

132

133

def power(a, size=None):

134

"""Power distribution samples."""

135

136

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

137

"""Rayleigh distribution samples."""

138

139

def chisquare(df, size=None):

140

"""Chi-square distribution samples."""

141

142

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

143

"""F distribution samples."""

144

145

def t(df, size=None):

146

"""Student's t distribution samples."""

147

```

148

149

### Sampling and Permutation

150

151

Functions for sampling and permutation operations.

152

153

```python { .api }

154

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

155

"""Generate random sample from given array.

156

157

Args:

158

a: Array to sample from or integer for range

159

size: Output shape

160

replace: Whether to sample with replacement

161

p: Probabilities for each element

162

163

Returns:

164

cupy.ndarray: Random samples

165

"""

166

167

def shuffle(x):

168

"""Modify array in-place by shuffling its contents.

169

170

Args:

171

x: Array to shuffle

172

"""

173

174

def permutation(x):

175

"""Randomly permute array or return permuted range.

176

177

Args:

178

x: Array to permute or integer for range

179

180

Returns:

181

cupy.ndarray: Permuted array

182

"""

183

```

184

185

### Generator Interface

186

187

Modern random number generator interface with multiple algorithms.

188

189

```python { .api }

190

class Generator:

191

"""Random number generator with multiple algorithms.

192

193

Provides access to various bit generators and distribution methods.

194

"""

195

def __init__(self, bit_generator):

196

"""Initialize generator with bit generator.

197

198

Args:

199

bit_generator: Bit generator instance

200

"""

201

202

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

203

"""Random floats in [0.0, 1.0)."""

204

205

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

206

"""Random integers from discrete uniform distribution."""

207

208

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

209

"""Standard normal distribution samples."""

210

211

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

212

"""Normal distribution samples."""

213

214

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

215

"""Uniform distribution samples."""

216

217

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

218

"""Exponential distribution samples."""

219

220

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

221

"""Gamma distribution samples."""

222

223

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

224

"""Beta distribution samples."""

225

226

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

227

"""Binomial distribution samples."""

228

229

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

230

"""Poisson distribution samples."""

231

232

def choice(self, a, size=None, replace=True, p=None, axis=0, shuffle=True):

233

"""Generate random sample from array."""

234

235

def shuffle(self, x, axis=0):

236

"""Shuffle array in-place along axis."""

237

238

def permutation(self, x, axis=0):

239

"""Return permuted array."""

240

241

class BitGenerator:

242

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

243

pass

244

245

class XORWOW(BitGenerator):

246

"""XORWOW bit generator."""

247

def __init__(self, seed=None):

248

pass

249

250

class MRG32k3a(BitGenerator):

251

"""MRG32k3a bit generator."""

252

def __init__(self, seed=None):

253

pass

254

255

class Philox(BitGenerator):

256

"""Philox bit generator."""

257

def __init__(self, seed=None, counter=None, key=None):

258

pass

259

260

def default_rng(seed=None):

261

"""Create default random generator.

262

263

Args:

264

seed: Random seed

265

266

Returns:

267

Generator: Random number generator

268

"""

269

```

270

271

### Random State Management

272

273

Control and manage random number generator state.

274

275

```python { .api }

276

class RandomState:

277

"""Random number generator state container.

278

279

Provides NumPy-compatible random state management.

280

"""

281

def __init__(self, seed=None):

282

"""Initialize random state.

283

284

Args:

285

seed: Random seed

286

"""

287

288

def seed(self, seed=None):

289

"""Seed the generator."""

290

291

def get_state(self):

292

"""Get current state."""

293

294

def set_state(self, state):

295

"""Set generator state."""

296

297

def random_sample(self, size=None):

298

"""Random floats in [0.0, 1.0)."""

299

300

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

301

"""Random integers."""

302

303

def randn(self, *args):

304

"""Standard normal samples."""

305

306

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

307

"""Normal distribution samples."""

308

309

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

310

"""Uniform distribution samples."""

311

312

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

313

"""Random sample from array."""

314

315

def shuffle(self, x):

316

"""Shuffle array in-place."""

317

318

def permutation(self, x):

319

"""Return permuted array."""

320

321

def get_random_state():

322

"""Get current global random state."""

323

324

def set_random_state(state):

325

"""Set global random state."""

326

```

327

328

## Usage Examples

329

330

### Basic Random Number Generation

331

332

```python

333

import cupy as cp

334

335

# Set seed for reproducibility

336

cp.random.seed(42)

337

338

# Generate random arrays

339

uniform_vals = cp.random.random((3, 4)) # Uniform [0, 1)

340

normal_vals = cp.random.randn(5, 5) # Standard normal

341

integers = cp.random.randint(0, 10, (2, 3)) # Random integers

342

343

print("Uniform values:\n", uniform_vals)

344

print("Normal values:\n", normal_vals)

345

print("Random integers:\n", integers)

346

```

347

348

### Probability Distributions

349

350

```python

351

# Normal distribution with custom parameters

352

normal_custom = cp.random.normal(loc=5.0, scale=2.0, size=(1000,))

353

354

# Exponential distribution

355

exponential_vals = cp.random.exponential(scale=2.0, size=500)

356

357

# Gamma distribution

358

gamma_vals = cp.random.gamma(shape=2.0, scale=1.0, size=1000)

359

360

# Binomial distribution

361

binomial_vals = cp.random.binomial(n=10, p=0.3, size=1000)

362

363

# Poisson distribution

364

poisson_vals = cp.random.poisson(lam=3.0, size=1000)

365

366

# Verify distribution properties

367

print(f"Normal mean: {normal_custom.mean():.2f} (expected: 5.0)")

368

print(f"Normal std: {normal_custom.std():.2f} (expected: 2.0)")

369

```

370

371

### Sampling and Choice Operations

372

373

```python

374

# Sample from existing array

375

data = cp.arange(100)

376

samples = cp.random.choice(data, size=10, replace=False)

377

378

# Weighted sampling

379

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

380

choices = cp.array(['A', 'B', 'C', 'D'])

381

weighted_samples = cp.random.choice(choices, size=1000, p=weights)

382

383

# Shuffling arrays

384

deck = cp.arange(52) # Deck of cards

385

cp.random.shuffle(deck)

386

print("Shuffled deck:", deck[:10])

387

388

# Permutation (returns copy)

389

original = cp.array([1, 2, 3, 4, 5])

390

permuted = cp.random.permutation(original)

391

print("Original:", original)

392

print("Permuted:", permuted)

393

```

394

395

### Advanced Generator Interface

396

397

```python

398

# Create generator with specific bit generator

399

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

400

401

# Generate samples using modern interface

402

samples = rng.random(size=(5, 5))

403

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

404

normal_samples = rng.normal(loc=0, scale=1, size=1000)

405

406

# Use different bit generators for different properties

407

philox_gen = cp.random.Generator(cp.random.Philox(seed=42))

408

xorwow_gen = cp.random.Generator(cp.random.XORWOW(seed=42))

409

410

# Philox is good for parallel generation

411

parallel_samples = philox_gen.normal(size=(10000,))

412

413

# XORWOW is fast for sequential generation

414

sequential_samples = xorwow_gen.uniform(size=(10000,))

415

```

416

417

### Random State Management

418

419

```python

420

# Save and restore random state

421

state = cp.random.get_state()

422

423

# Generate some numbers

424

first_batch = cp.random.random(5)

425

426

# Restore state and generate again

427

cp.random.set_state(state)

428

second_batch = cp.random.random(5)

429

430

# Should be identical

431

print("First batch: ", first_batch)

432

print("Second batch:", second_batch)

433

print("Identical:", cp.allclose(first_batch, second_batch))

434

435

# Use RandomState class for multiple generators

436

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

437

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

438

439

batch1 = rs1.random(3)

440

batch2 = rs2.random(3)

441

print("Generator 1:", batch1)

442

print("Generator 2:", batch2)

443

```

444

445

### Monte Carlo Simulations

446

447

```python

448

# Estimate π using Monte Carlo method

449

n_samples = 1000000

450

x = cp.random.uniform(-1, 1, n_samples)

451

y = cp.random.uniform(-1, 1, n_samples)

452

453

# Points inside unit circle

454

inside_circle = (x**2 + y**2) <= 1

455

pi_estimate = 4 * cp.mean(inside_circle)

456

457

print(f"π estimate: {pi_estimate:.4f}")

458

print(f"Error: {abs(pi_estimate - cp.pi):.4f}")

459

460

# Option pricing with geometric Brownian motion

461

S0 = 100 # Initial stock price

462

T = 1.0 # Time to maturity

463

r = 0.05 # Risk-free rate

464

sigma = 0.2 # Volatility

465

n_paths = 10000

466

467

# Generate random walks

468

dt = T / 252 # Daily steps

469

random_increments = cp.random.normal(0, 1, (n_paths, 252))

470

price_paths = S0 * cp.exp(cp.cumsum((r - 0.5*sigma**2)*dt +

471

sigma*cp.sqrt(dt)*random_increments, axis=1))

472

473

final_prices = price_paths[:, -1]

474

print(f"Expected final price: {cp.mean(final_prices):.2f}")

475

```

476

477

### Statistical Testing and Validation

478

479

```python

480

# Generate large sample and test properties

481

n = 100000

482

normal_samples = cp.random.normal(2.0, 1.5, n)

483

484

# Calculate sample statistics

485

sample_mean = cp.mean(normal_samples)

486

sample_std = cp.std(normal_samples, ddof=1)

487

488

print(f"Sample mean: {sample_mean:.4f} (expected: 2.0)")

489

print(f"Sample std: {sample_std:.4f} (expected: 1.5)")

490

491

# Test uniform distribution

492

uniform_samples = cp.random.uniform(0, 1, n)

493

print(f"Uniform min: {cp.min(uniform_samples):.4f}")

494

print(f"Uniform max: {cp.max(uniform_samples):.4f}")

495

print(f"Uniform mean: {cp.mean(uniform_samples):.4f} (expected: 0.5)")

496

```

497

498

### Performance Considerations

499

500

```python

501

# Large array generation

502

large_size = (10000, 10000)

503

504

# Time different operations

505

import time

506

507

start = time.time()

508

large_uniform = cp.random.random(large_size)

509

end = time.time()

510

print(f"Large uniform generation: {end - start:.3f} seconds")

511

512

start = time.time()

513

large_normal = cp.random.randn(*large_size)

514

end = time.time()

515

print(f"Large normal generation: {end - start:.3f} seconds")

516

517

# Memory usage

518

print(f"Array size: {large_uniform.nbytes / 1024**3:.2f} GB")

519

```