or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-operations.mdcuda-interface.mdcustom-kernels.mdindex.mdlinear-algebra.mdmathematical-functions.mdrandom-generation.mdscipy-extensions.mdstatistics.md

random-generation.mddocs/

0

# Random Number Generation

1

2

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.

3

4

## Capabilities

5

6

### Basic Random Functions

7

8

Core random number generation functions for common distributions.

9

10

```python { .api }

11

def random(size=None, dtype=float):

12

"""

13

Random values in half-open interval [0.0, 1.0).

14

15

Parameters:

16

- size: int/tuple, output shape

17

- dtype: data type of output

18

19

Returns:

20

cupy.ndarray: Random values from uniform distribution

21

"""

22

23

def rand(*args):

24

"""Random values in half-open interval [0.0, 1.0) with given shape."""

25

26

def randn(*args):

27

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

28

29

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

30

"""

31

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

32

33

Parameters:

34

- low: int, lowest integer to draw

35

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

36

- size: int/tuple, output shape

37

- dtype: data type of output

38

39

Returns:

40

cupy.ndarray: Random integers

41

"""

42

43

def seed(seed=None):

44

"""Seed the random number generator."""

45

46

def get_random_state():

47

"""Get current random state."""

48

49

def set_random_state(state):

50

"""Set random state."""

51

```

52

53

### Uniform Distributions

54

55

Random sampling from uniform distributions over various intervals.

56

57

```python { .api }

58

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

59

"""

60

Draw samples from uniform distribution.

61

62

Parameters:

63

- low: float, lower boundary of output interval

64

- high: float, upper boundary of output interval

65

- size: int/tuple, output shape

66

67

Returns:

68

cupy.ndarray: Random samples from uniform distribution

69

"""

70

71

def random_sample(size=None):

72

"""Random floats in half-open interval [0.0, 1.0)."""

73

74

def sample(size=None):

75

"""Alias for random_sample."""

76

77

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

78

"""Random integers between low and high, inclusive."""

79

```

80

81

### Normal and Related Distributions

82

83

Gaussian and related continuous probability distributions.

84

85

```python { .api }

86

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

87

"""

88

Draw samples from normal (Gaussian) distribution.

89

90

Parameters:

91

- loc: float, mean of distribution

92

- scale: float, standard deviation

93

- size: int/tuple, output shape

94

95

Returns:

96

cupy.ndarray: Random samples from normal distribution

97

"""

98

99

def standard_normal(size=None):

100

"""Draw samples from standard normal distribution (mean=0, std=1)."""

101

102

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

103

"""Draw samples from log-normal distribution."""

104

105

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

106

"""

107

Draw samples from multivariate normal distribution.

108

109

Parameters:

110

- mean: array_like, mean of distribution

111

- cov: array_like, covariance matrix

112

- size: int/tuple, shape of output

113

- check_valid: str, behavior for non-positive-semidefinite covariance

114

- tol: float, tolerance for covariance matrix validation

115

116

Returns:

117

cupy.ndarray: Random samples from multivariate normal

118

"""

119

```

120

121

### Discrete Distributions

122

123

Random sampling from discrete probability distributions.

124

125

```python { .api }

126

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

127

"""

128

Draw samples from binomial distribution.

129

130

Parameters:

131

- n: int, number of trials

132

- p: float, probability of success in each trial

133

- size: int/tuple, output shape

134

135

Returns:

136

cupy.ndarray: Random samples from binomial distribution

137

"""

138

139

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

140

"""Draw samples from Poisson distribution."""

141

142

def geometric(p, size=None):

143

"""Draw samples from geometric distribution."""

144

145

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

146

"""Draw samples from negative binomial distribution."""

147

148

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

149

"""Draw samples from hypergeometric distribution."""

150

```

151

152

### Continuous Distributions

153

154

Various continuous probability distributions for statistical modeling.

155

156

```python { .api }

157

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

158

"""

159

Draw samples from exponential distribution.

160

161

Parameters:

162

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

163

- size: int/tuple, output shape

164

165

Returns:

166

cupy.ndarray: Random samples from exponential distribution

167

"""

168

169

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

170

"""Draw samples from Gamma distribution."""

171

172

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

173

"""Draw samples from Beta distribution."""

174

175

def chisquare(df, size=None):

176

"""Draw samples from chi-square distribution."""

177

178

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

179

"""Draw samples from F distribution."""

180

181

def weibull(a, size=None):

182

"""Draw samples from Weibull distribution."""

183

184

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

185

"""Draw samples from Laplace distribution."""

186

187

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

188

"""Draw samples from logistic distribution."""

189

190

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

191

"""Draw samples from Gumbel distribution."""

192

193

def pareto(a, size=None):

194

"""Draw samples from Pareto II distribution."""

195

196

def power(a, size=None):

197

"""Draw samples from power distribution."""

198

199

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

200

"""Draw samples from Rayleigh distribution."""

201

202

def standard_cauchy(size=None):

203

"""Draw samples from standard Cauchy distribution."""

204

205

def standard_exponential(size=None):

206

"""Draw samples from standard exponential distribution."""

207

208

def standard_gamma(shape, size=None):

209

"""Draw samples from standard Gamma distribution."""

210

211

def standard_t(df, size=None):

212

"""Draw samples from Student's t-distribution."""

213

214

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

215

"""Draw samples from triangular distribution."""

216

217

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

218

"""Draw samples from von Mises distribution."""

219

220

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

221

"""Draw samples from Wald (inverse Gaussian) distribution."""

222

223

def zipf(a, size=None):

224

"""Draw samples from Zipf distribution."""

225

```

226

227

### Random Sampling and Choice

228

229

Functions for random sampling and selection from existing data.

230

231

```python { .api }

232

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

233

"""

234

Generate random sample from given 1-D array.

235

236

Parameters:

237

- a: array_like/int, input array or integer (range)

238

- size: int/tuple, output shape

239

- replace: bool, whether sample is with/without replacement

240

- p: array_like, probabilities associated with each entry

241

242

Returns:

243

cupy.ndarray: Random samples from input array

244

"""

245

246

def shuffle(x):

247

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

248

249

def permutation(x):

250

"""Randomly permute sequence or return permuted range."""

251

```

252

253

### Random State Management

254

255

Control and management of random number generator state.

256

257

```python { .api }

258

class RandomState:

259

"""

260

Container for random number generator state.

261

262

Parameters:

263

- seed: int, seed for random number generator

264

"""

265

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

266

267

def seed(self, seed=None):

268

"""Seed random number generator."""

269

270

def get_state(self):

271

"""Return tuple representing internal state."""

272

273

def set_state(self, state):

274

"""Set internal state from tuple."""

275

276

# Distribution methods (same as module-level functions)

277

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

278

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

279

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

280

# ... all other distribution methods

281

```

282

283

## Usage Examples

284

285

### Basic Random Number Generation

286

287

```python

288

import cupy as cp

289

290

# Set seed for reproducibility

291

cp.random.seed(42)

292

293

# Generate uniform random numbers

294

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

295

uniform_range = cp.random.uniform(-1, 1, (500, 500))

296

297

# Generate normal random numbers

298

normal_data = cp.random.normal(0, 1, (1000, 1000))

299

custom_normal = cp.random.normal(10, 2.5, (100, 100))

300

301

# Generate random integers

302

random_ints = cp.random.randint(0, 100, (50, 50))

303

dice_rolls = cp.random.randint(1, 7, 1000)

304

```

305

306

### Statistical Distributions

307

308

```python

309

# Exponential distribution (modeling waiting times)

310

waiting_times = cp.random.exponential(2.0, 10000)

311

312

# Gamma distribution (modeling continuous positive values)

313

gamma_samples = cp.random.gamma(2, 2, 5000)

314

315

# Beta distribution (modeling proportions)

316

proportions = cp.random.beta(2, 5, 1000)

317

318

# Poisson distribution (modeling count data)

319

event_counts = cp.random.poisson(3.5, 10000)

320

321

# Binomial distribution (modeling success/failure trials)

322

successes = cp.random.binomial(100, 0.3, 5000)

323

```

324

325

### Multivariate Distributions

326

327

```python

328

# Multivariate normal distribution

329

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

330

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

331

mvn_samples = cp.random.multivariate_normal(mean, cov, 1000)

332

333

# Multiple correlated variables

334

n_vars = 5

335

mean = cp.zeros(n_vars)

336

correlation = 0.3

337

cov = correlation * cp.ones((n_vars, n_vars))

338

cp.fill_diagonal(cov, 1.0)

339

correlated_data = cp.random.multivariate_normal(mean, cov, 10000)

340

```

341

342

### Random Sampling and Selection

343

344

```python

345

# Random choice from array

346

data = cp.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

347

random_samples = cp.random.choice(data, size=100, replace=True)

348

349

# Weighted random sampling

350

weights = cp.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])

351

weighted_samples = cp.random.choice(data, size=100, p=weights)

352

353

# Random permutation

354

permuted_data = cp.random.permutation(data)

355

356

# Shuffle in place

357

cp.random.shuffle(data) # Modifies data array

358

```

359

360

### Monte Carlo Simulations

361

362

```python

363

# Estimate π using Monte Carlo method

364

n_samples = 1000000

365

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

366

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

367

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

368

pi_estimate = 4 * cp.mean(inside_circle)

369

370

# Random walk simulation

371

n_steps = 10000

372

steps = cp.random.choice([-1, 1], size=n_steps)

373

position = cp.cumsum(steps)

374

375

# Portfolio simulation

376

n_assets = 10

377

n_scenarios = 100000

378

returns = cp.random.multivariate_normal(

379

mean=cp.full(n_assets, 0.08), # 8% expected return

380

cov=0.04 * cp.eye(n_assets), # 20% volatility, uncorrelated

381

size=n_scenarios

382

)

383

```

384

385

### Advanced Random State Management

386

387

```python

388

# Create separate random state

389

rng = cp.random.RandomState(12345)

390

391

# Generate samples with specific state

392

samples1 = rng.normal(0, 1, 1000)

393

samples2 = rng.uniform(0, 1, 1000)

394

395

# Save and restore state

396

state = rng.get_state()

397

more_samples = rng.normal(0, 1, 1000)

398

399

# Restore previous state

400

rng.set_state(state)

401

repeated_samples = rng.normal(0, 1, 1000) # Same as more_samples

402

403

# Multiple independent generators

404

rng1 = cp.random.RandomState(111)

405

rng2 = cp.random.RandomState(222)

406

407

# Generate independent sequences

408

seq1 = rng1.random(1000)

409

seq2 = rng2.random(1000)

410

```

411

412

### Time Series and Sequential Data

413

414

```python

415

# Generate autoregressive time series

416

n_points = 10000

417

phi = 0.7 # Autoregressive parameter

418

noise = cp.random.normal(0, 1, n_points)

419

ar_series = cp.zeros(n_points)

420

421

for i in range(1, n_points):

422

ar_series[i] = phi * ar_series[i-1] + noise[i]

423

424

# Generate random walk with drift

425

drift = 0.01

426

innovations = cp.random.normal(drift, 0.1, n_points)

427

random_walk = cp.cumsum(innovations)

428

429

# Geometric Brownian motion (stock price model)

430

S0 = 100 # Initial price

431

mu = 0.1 # Drift

432

sigma = 0.2 # Volatility

433

dt = 1/252 # Daily time step

434

435

dW = cp.random.normal(0, cp.sqrt(dt), n_points)

436

log_returns = (mu - 0.5*sigma**2)*dt + sigma*dW

437

stock_prices = S0 * cp.exp(cp.cumsum(log_returns))

438

```