or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-operations.mdcuda-interface.mdfft-operations.mdindex.mdinput-output.mdlinear-algebra.mdmath-operations.mdrandom-generation.mdscipy-extensions.md

random-generation.mddocs/

0

# Random Number Generation

1

2

GPU-accelerated random number generation supporting multiple bit generators, probability distributions, and statistical sampling operations for simulation, machine learning, and scientific computing.

3

4

## Capabilities

5

6

### Random Number Generators

7

8

Core random number generation interfaces and bit generators.

9

10

```python { .api }

11

class random.Generator:

12

"""

13

Container for bit generators and methods for random number generation.

14

15

Parameters:

16

- bit_generator: BitGenerator, source of randomness

17

"""

18

def __init__(self, bit_generator): ...

19

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

20

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

21

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

22

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

23

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

24

def beta(self, a, b, size=None, dtype=cp.float64): ...

25

def binomial(self, n, p, size=None, dtype=cp.int64): ...

26

def chisquare(self, df, size=None, dtype=cp.float64): ...

27

def exponential(self, scale=1.0, size=None, dtype=cp.float64): ...

28

def gamma(self, shape, scale=1.0, size=None, dtype=cp.float64): ...

29

def geometric(self, p, size=None, dtype=cp.int64): ...

30

def gumbel(self, loc=0.0, scale=1.0, size=None, dtype=cp.float64): ...

31

def laplace(self, loc=0.0, scale=1.0, size=None, dtype=cp.float64): ...

32

def logistic(self, loc=0.0, scale=1.0, size=None, dtype=cp.float64): ...

33

def lognormal(self, mean=0.0, sigma=1.0, size=None, dtype=cp.float64): ...

34

def normal(self, loc=0.0, scale=1.0, size=None, dtype=cp.float64): ...

35

def pareto(self, a, size=None, dtype=cp.float64): ...

36

def poisson(self, lam=1.0, size=None, dtype=cp.int64): ...

37

def rayleigh(self, scale=1.0, size=None, dtype=cp.float64): ...

38

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

39

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

40

def standard_gamma(self, shape, size=None, dtype=cp.float64): ...

41

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

42

def standard_t(self, df, size=None, dtype=cp.float64): ...

43

def triangular(self, left, mode, right, size=None, dtype=cp.float64): ...

44

def uniform(self, low=0.0, high=1.0, size=None, dtype=cp.float64): ...

45

def vonmises(self, mu, kappa, size=None, dtype=cp.float64): ...

46

def wald(self, mean, scale, size=None, dtype=cp.float64): ...

47

def weibull(self, a, size=None, dtype=cp.float64): ...

48

49

def random.default_rng(seed=None):

50

"""

51

Construct Generator with default BitGenerator (XORWOW).

52

53

Parameters:

54

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

55

56

Returns:

57

Generator, initialized generator object

58

"""

59

60

class random.BitGenerator:

61

"""

62

Base class for bit generators."""

63

def __init__(self): ...

64

@property

65

def state(self): ...

66

@state.setter

67

def state(self, value): ...

68

69

class random.XORWOW(BitGenerator):

70

"""

71

XORWOW bit generator (default).

72

73

Parameters:

74

- seed: int, array-like, or SeedSequence

75

"""

76

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

77

78

class random.MRG32k3a(BitGenerator):

79

"""

80

MRG32k3a bit generator.

81

82

Parameters:

83

- seed: int, array-like, or SeedSequence

84

"""

85

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

86

87

class random.Philox4x3210(BitGenerator):

88

"""

89

Philox 4x32-10 bit generator.

90

91

Parameters:

92

- seed: int, array-like, or SeedSequence

93

"""

94

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

95

```

96

97

### Legacy Random Interface

98

99

Legacy NumPy-compatible random number interface.

100

101

```python { .api }

102

class random.RandomState:

103

"""

104

Legacy random number generator state.

105

106

Parameters:

107

- seed: int, array-like, or None

108

"""

109

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

110

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

111

def get_state(self): ...

112

def set_state(self, state): ...

113

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

114

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

115

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

116

def random_integers(self, low, high=None, size=None): ...

117

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

118

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

119

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

120

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

121

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

122

def shuffle(self, x): ...

123

def permutation(self, x): ...

124

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

125

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

126

def chisquare(self, df, size=None): ...

127

def dirichlet(self, alpha, size=None): ...

128

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

129

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

130

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

131

def geometric(self, p, size=None): ...

132

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

133

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

134

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

135

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

136

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

137

def logseries(self, p, size=None): ...

138

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

139

def multivariate_normal(self, mean, cov, size=None): ...

140

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

141

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

142

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

143

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

144

def pareto(self, a, size=None): ...

145

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

146

def power(self, a, size=None): ...

147

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

148

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

149

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

150

def standard_gamma(self, shape, size=None): ...

151

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

152

def standard_t(self, df, size=None): ...

153

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

154

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

155

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

156

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

157

def weibull(self, a, size=None): ...

158

def zipf(self, a, size=None): ...

159

160

def random.seed(seed=None):

161

"""

162

Seed global random number generator.

163

164

Parameters:

165

- seed: int, array-like, or None

166

"""

167

168

def random.get_random_state():

169

"""

170

Get global RandomState instance.

171

172

Returns:

173

RandomState, global random state

174

"""

175

176

def random.set_random_state(state):

177

"""

178

Set global random state.

179

180

Parameters:

181

- state: RandomState, random state to set

182

"""

183

184

def random.reset_states():

185

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

186

```

187

188

### Simple Random Data

189

190

Convenience functions for basic random number generation.

191

192

```python { .api }

193

def random.rand(*args):

194

"""

195

Random values in [0, 1) with given shape.

196

197

Parameters:

198

- args: ints, shape dimensions

199

200

Returns:

201

cupy.ndarray, random values

202

"""

203

204

def random.randn(*args):

205

"""

206

Standard normal random values with given shape.

207

208

Parameters:

209

- args: ints, shape dimensions

210

211

Returns:

212

cupy.ndarray, normally distributed values

213

"""

214

215

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

216

"""

217

Random integers from low (inclusive) to high (exclusive).

218

219

Parameters:

220

- low: int or array-like, lowest value

221

- high: int or array-like, highest value

222

- size: int or tuple, output shape

223

- dtype: data type

224

225

Returns:

226

cupy.ndarray, random integers

227

"""

228

229

def random.random_integers(low, high=None, size=None):

230

"""

231

Random integers from low to high, inclusive (deprecated).

232

233

Parameters:

234

- low: int, lowest value

235

- high: int, highest value

236

- size: int or tuple, output shape

237

238

Returns:

239

cupy.ndarray, random integers

240

"""

241

242

def random.random_sample(size=None):

243

"""

244

Random floats in [0.0, 1.0) with given shape.

245

246

Parameters:

247

- size: int or tuple, output shape

248

249

Returns:

250

cupy.ndarray, random values

251

"""

252

253

def random.random(size=None):

254

"""

255

Alias for random_sample.

256

257

Parameters:

258

- size: int or tuple, output shape

259

260

Returns:

261

cupy.ndarray, random values

262

"""

263

264

def random.bytes(length):

265

"""

266

Random bytes (CPU-based, wrapper for numpy.random.bytes).

267

268

Parameters:

269

- length: int, number of bytes

270

271

Returns:

272

bytes, random byte string

273

"""

274

```

275

276

### Probability Distributions

277

278

Statistical probability distributions for sampling.

279

280

```python { .api }

281

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

282

"""

283

Beta distribution samples.

284

285

Parameters:

286

- a: float or array-like, alpha parameter

287

- b: float or array-like, beta parameter

288

- size: int or tuple, output shape

289

290

Returns:

291

cupy.ndarray, beta distributed samples

292

"""

293

294

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

295

"""

296

Binomial distribution samples.

297

298

Parameters:

299

- n: int or array-like, number of trials

300

- p: float or array-like, success probability

301

- size: int or tuple, output shape

302

303

Returns:

304

cupy.ndarray, binomial distributed samples

305

"""

306

307

def random.chisquare(df, size=None):

308

"""

309

Chi-square distribution samples.

310

311

Parameters:

312

- df: float or array-like, degrees of freedom

313

- size: int or tuple, output shape

314

315

Returns:

316

cupy.ndarray, chi-square distributed samples

317

"""

318

319

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

320

"""

321

Exponential distribution samples.

322

323

Parameters:

324

- scale: float or array-like, scale parameter

325

- size: int or tuple, output shape

326

327

Returns:

328

cupy.ndarray, exponentially distributed samples

329

"""

330

331

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

332

"""

333

Gamma distribution samples.

334

335

Parameters:

336

- shape: float or array-like, shape parameter

337

- scale: float or array-like, scale parameter

338

- size: int or tuple, output shape

339

340

Returns:

341

cupy.ndarray, gamma distributed samples

342

"""

343

344

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

345

"""

346

Normal (Gaussian) distribution samples.

347

348

Parameters:

349

- loc: float or array-like, mean

350

- scale: float or array-like, standard deviation

351

- size: int or tuple, output shape

352

353

Returns:

354

cupy.ndarray, normally distributed samples

355

"""

356

357

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

358

"""

359

Poisson distribution samples.

360

361

Parameters:

362

- lam: float or array-like, rate parameter

363

- size: int or tuple, output shape

364

365

Returns:

366

cupy.ndarray, Poisson distributed samples

367

"""

368

369

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

370

"""

371

Uniform distribution samples.

372

373

Parameters:

374

- low: float or array-like, lower bound

375

- high: float or array-like, upper bound

376

- size: int or tuple, output shape

377

378

Returns:

379

cupy.ndarray, uniformly distributed samples

380

"""

381

382

def random.multivariate_normal(mean, cov, size=None):

383

"""

384

Multivariate normal distribution samples.

385

386

Parameters:

387

- mean: array-like, mean vector

388

- cov: array-like, covariance matrix

389

- size: int or tuple, output shape

390

391

Returns:

392

cupy.ndarray, multivariate normal samples

393

"""

394

```

395

396

### Permutations and Sampling

397

398

Functions for permutations, shuffling, and sampling.

399

400

```python { .api }

401

def random.shuffle(x):

402

"""

403

Modify sequence in-place by shuffling its contents.

404

405

Parameters:

406

- x: array-like, sequence to shuffle

407

"""

408

409

def random.permutation(x):

410

"""

411

Randomly permute sequence or return permuted range.

412

413

Parameters:

414

- x: int or array-like, sequence to permute

415

416

Returns:

417

cupy.ndarray, permuted sequence

418

"""

419

420

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

421

"""

422

Generate random sample from given 1-D array.

423

424

Parameters:

425

- a: int or array-like, source array

426

- size: int or tuple, output shape

427

- replace: bool, sample with replacement

428

- p: array-like, probabilities for each element

429

430

Returns:

431

cupy.ndarray, sampled values

432

"""

433

434

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

435

"""

436

Multinomial distribution samples.

437

438

Parameters:

439

- n: int, number of trials

440

- pvals: array-like, probabilities for each outcome

441

- size: int or tuple, output shape

442

443

Returns:

444

cupy.ndarray, multinomial samples

445

"""

446

```

447

448

## Usage Examples

449

450

### Basic Random Number Generation

451

452

```python

453

import cupy as cp

454

455

# Set seed for reproducibility

456

cp.random.seed(42)

457

458

# Basic random arrays

459

random_uniform = cp.random.rand(1000, 1000)

460

random_normal = cp.random.randn(1000, 1000)

461

random_integers = cp.random.randint(0, 100, size=(100, 100))

462

463

# Specific distributions

464

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

465

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

466

normal_samples = cp.random.normal(loc=0.0, scale=1.0, size=10000)

467

```

468

469

### Using the New Generator API

470

471

```python

472

import cupy as cp

473

474

# Create generator with specific bit generator

475

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

476

477

# Generate random data

478

uniform_data = rng.random((1000, 1000))

479

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

480

normal_data = rng.normal(0, 1, size=(500, 500))

481

482

# Sample from discrete distribution

483

categories = rng.choice(['A', 'B', 'C', 'D'], size=1000, p=[0.1, 0.3, 0.4, 0.2])

484

485

# Different bit generators

486

xorwow_rng = cp.random.Generator(cp.random.XORWOW(seed=123))

487

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

488

mrg_rng = cp.random.Generator(cp.random.MRG32k3a(seed=789))

489

```

490

491

### Statistical Sampling

492

493

```python

494

import cupy as cp

495

496

# Monte Carlo simulation

497

n_samples = 1000000

498

rng = cp.random.default_rng(42)

499

500

# Simulate stock prices using geometric Brownian motion

501

dt = 1/252 # Daily time step

502

mu = 0.05 # Drift

503

sigma = 0.2 # Volatility

504

S0 = 100 # Initial price

505

506

# Generate random returns

507

random_returns = rng.normal(0, 1, size=n_samples)

508

price_changes = (mu - 0.5 * sigma**2) * dt + sigma * cp.sqrt(dt) * random_returns

509

final_prices = S0 * cp.exp(price_changes)

510

511

# Statistical analysis

512

mean_price = cp.mean(final_prices)

513

std_price = cp.std(final_prices)

514

percentiles = cp.percentile(final_prices, [5, 50, 95])

515

```

516

517

### Permutations and Shuffling

518

519

```python

520

import cupy as cp

521

522

# Create array to shuffle

523

data = cp.arange(100)

524

525

# In-place shuffle

526

cp.random.shuffle(data)

527

528

# Create permutation without modifying original

529

original = cp.arange(20)

530

permuted = cp.random.permutation(original)

531

532

# Random sampling

533

large_array = cp.arange(10000)

534

random_sample = cp.random.choice(large_array, size=100, replace=False)

535

536

# Weighted sampling

537

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

538

probabilities = cp.array([0.1, 0.2, 0.3, 0.25, 0.15])

539

weighted_sample = cp.random.choice(values, size=1000, p=probabilities)

540

```

541

542

### Multivariate Distributions

543

544

```python

545

import cupy as cp

546

547

# Multivariate normal distribution

548

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

549

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

550

551

# Generate correlated samples

552

mvn_samples = cp.random.multivariate_normal(

553

mean_vector, covariance_matrix, size=1000

554

)

555

556

# Analyze correlation

557

correlation = cp.corrcoef(mvn_samples.T)

558

print("Sample correlation matrix:")

559

print(cp.asnumpy(correlation))

560

561

# Multinomial distribution

562

n_trials = 100

563

outcome_probs = cp.array([0.2, 0.3, 0.3, 0.2])

564

multinomial_samples = cp.random.multinomial(n_trials, outcome_probs, size=1000)

565

```

566

567

### Performance Considerations

568

569

```python

570

import cupy as cp

571

import time

572

573

# Compare different methods for large arrays

574

n = 10000000

575

576

# Method 1: Single large array generation

577

start = time.time()

578

large_array = cp.random.random(n)

579

time1 = time.time() - start

580

581

# Method 2: Multiple smaller arrays (less efficient)

582

start = time.time()

583

small_arrays = [cp.random.random(1000) for _ in range(n//1000)]

584

combined = cp.concatenate(small_arrays)

585

time2 = time.time() - start

586

587

print(f"Large array generation: {time1:.4f} seconds")

588

print(f"Small arrays generation: {time2:.4f} seconds")

589

590

# Use appropriate data types for memory efficiency

591

float32_array = cp.random.random(n, dtype=cp.float32) # Half the memory

592

int16_array = cp.random.randint(0, 1000, size=n, dtype=cp.int16) # Even less memory

593

```