or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-creation.mdarray-statistics.mddata-types.mdfft.mdindex.mdinput-output.mdlinear-algebra.mdmasked-arrays.mdmathematical-functions.mdpolynomial.mdrandom-generation.mdsearching-sorting.md

random-generation.mddocs/

0

# Random Number Generation

1

2

Comprehensive random number generation through numpy.random. Provides random sampling from various probability distributions, random choice operations, and modern BitGenerator infrastructure for high-quality pseudorandom numbers.

3

4

## Core Generator Interface

5

6

### Modern Generator API

7

8

The recommended interface for random number generation.

9

10

```python { .api }

11

def random.default_rng(seed=None):

12

"""

13

Construct new Generator with default BitGenerator (PCG64).

14

15

Parameters:

16

- seed: {None, int, array_like, BitGenerator}, random seed

17

18

Returns:

19

Generator: New random number generator

20

"""

21

22

class random.Generator:

23

"""

24

Container for BitGenerator and provides random number generation methods.

25

"""

26

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

27

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

28

29

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

30

"""Random integers from low to high"""

31

32

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

33

"""Normal (Gaussian) distribution"""

34

35

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

36

"""Uniform distribution"""

37

38

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

39

"""Random sample from array"""

40

```

41

42

### Legacy RandomState Interface

43

44

Compatibility interface (legacy, use Generator for new code).

45

46

```python { .api }

47

class random.RandomState:

48

"""

49

Legacy random number generator interface.

50

"""

51

def __init__(self, seed=None):

52

"""Initialize RandomState"""

53

54

def random_sample(self, size=None):

55

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

56

57

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

58

"""Random integers"""

59

60

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

61

"""Normal distribution"""

62

```

63

64

## Distribution Functions (Legacy Interface)

65

66

### Uniform Distributions

67

68

```python { .api }

69

def random.random(size=None):

70

"""

71

Return random floats in half-open interval [0.0, 1.0).

72

73

Parameters:

74

- size: int or tuple, output shape

75

76

Returns:

77

ndarray or float: Random values

78

"""

79

80

def random.rand(*dn):

81

"""

82

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

83

84

Parameters:

85

- *dn: int, shape dimensions

86

87

Returns:

88

ndarray: Random values

89

"""

90

91

def random.randn(*dn):

92

"""

93

Random values from standard normal distribution.

94

95

Parameters:

96

- *dn: int, shape dimensions

97

98

Returns:

99

ndarray: Random values from N(0, 1)

100

"""

101

102

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

103

"""

104

Draw samples from uniform distribution.

105

106

Parameters:

107

- low, high: float, distribution bounds

108

- size: int or tuple, output shape

109

110

Returns:

111

ndarray: Random samples

112

"""

113

```

114

115

### Discrete Distributions

116

117

```python { .api }

118

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

119

"""

120

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

121

122

Parameters:

123

- low, high: int, range bounds

124

- size: int or tuple, output shape

125

- dtype: data-type, output type

126

127

Returns:

128

ndarray: Random integers

129

"""

130

131

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

132

"""

133

Draw samples from binomial distribution.

134

135

Parameters:

136

- n: int or array_like, number of trials

137

- p: float or array_like, probability of success

138

- size: int or tuple, output shape

139

140

Returns:

141

ndarray: Random samples

142

"""

143

144

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

145

"""

146

Draw samples from Poisson distribution.

147

148

Parameters:

149

- lam: float or array_like, expected intervals

150

- size: int or tuple, output shape

151

152

Returns:

153

ndarray: Random samples

154

"""

155

156

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

157

"""

158

Draw samples from geometric distribution.

159

160

Parameters:

161

- p: float or array_like, success probability

162

- size: int or tuple, output shape

163

164

Returns:

165

ndarray: Random samples

166

"""

167

```

168

169

### Continuous Distributions

170

171

```python { .api }

172

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

173

"""

174

Draw samples from normal (Gaussian) distribution.

175

176

Parameters:

177

- loc: float or array_like, mean

178

- scale: float or array_like, standard deviation

179

- size: int or tuple, output shape

180

181

Returns:

182

ndarray: Random samples

183

"""

184

185

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

186

"""

187

Draw samples from exponential distribution.

188

189

Parameters:

190

- scale: float or array_like, scale parameter

191

- size: int or tuple, output shape

192

193

Returns:

194

ndarray: Random samples

195

"""

196

197

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

198

"""

199

Draw samples from Gamma distribution.

200

201

Parameters:

202

- shape: float or array_like, shape parameter

203

- scale: float or array_like, scale parameter

204

- size: int or tuple, output shape

205

206

Returns:

207

ndarray: Random samples

208

"""

209

210

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

211

"""

212

Draw samples from Beta distribution.

213

214

Parameters:

215

- a, b: float or array_like, shape parameters

216

- size: int or tuple, output shape

217

218

Returns:

219

ndarray: Random samples

220

"""

221

222

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

223

"""

224

Draw samples from log-normal distribution.

225

226

Parameters:

227

- mean: float or array_like, mean of underlying normal

228

- sigma: float or array_like, std of underlying normal

229

- size: int or tuple, output shape

230

231

Returns:

232

ndarray: Random samples

233

"""

234

```

235

236

### Sampling and Permutation

237

238

```python { .api }

239

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

240

"""

241

Generate random sample from given 1-D array.

242

243

Parameters:

244

- a: 1-D array_like or int, array to sample from

245

- size: int or tuple, output shape

246

- replace: bool, whether sample with replacement

247

- p: 1-D array_like, probabilities for each element

248

249

Returns:

250

ndarray or scalar: Random samples

251

"""

252

253

def random.shuffle(x):

254

"""

255

Modify sequence in-place by shuffling its contents.

256

257

Parameters:

258

- x: array_like, sequence to shuffle

259

260

Returns:

261

None: Modifies x in-place

262

"""

263

264

def random.permutation(x):

265

"""

266

Randomly permute sequence or return permuted range.

267

268

Parameters:

269

- x: int or array_like, sequence to permute

270

271

Returns:

272

ndarray: Permuted sequence

273

"""

274

```

275

276

### Seeding and State Management

277

278

```python { .api }

279

def random.seed(seed=None):

280

"""

281

Seed the legacy random number generator.

282

283

Parameters:

284

- seed: {None, int, array_like}, seed value

285

286

Returns:

287

None: Seeds global RandomState

288

"""

289

290

def random.get_state():

291

"""

292

Return tuple representing internal state of generator.

293

294

Returns:

295

tuple: Current state of RandomState

296

"""

297

298

def random.set_state(state):

299

"""

300

Set internal state of generator from tuple.

301

302

Parameters:

303

- state: tuple, state from get_state()

304

305

Returns:

306

None: Sets RandomState to given state

307

"""

308

```

309

310

## BitGenerators

311

312

### Core BitGenerator Classes

313

314

```python { .api }

315

class random.BitGenerator:

316

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

317

318

class random.PCG64(BitGenerator):

319

"""PCG-64 bit generator (default, recommended)."""

320

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

321

322

class random.MT19937(BitGenerator):

323

"""Mersenne Twister bit generator."""

324

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

325

326

class random.Philox(BitGenerator):

327

"""Philox bit generator."""

328

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

329

330

class random.SFC64(BitGenerator):

331

"""SFC-64 bit generator."""

332

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

333

334

class random.SeedSequence:

335

"""Seed sequence for initializing bit generators."""

336

def __init__(self, entropy=None, spawn_key=(), pool_size=4): ...

337

```

338

339

## Usage Examples

340

341

### Modern Generator Interface

342

343

```python

344

import numpy as np

345

346

# Create generator (recommended approach)

347

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

348

349

# Generate random numbers

350

random_floats = rng.random(5) # [0.374, 0.950, 0.731, 0.598, 0.156]

351

random_ints = rng.integers(1, 10, 5) # [6, 2, 7, 8, 1]

352

353

# Sample from distributions

354

normal_vals = rng.normal(0, 1, 100) # 100 samples from N(0,1)

355

uniform_vals = rng.uniform(-1, 1, 50) # 50 samples from Uniform(-1,1)

356

357

# Random choice and sampling

358

data = np.array([1, 2, 3, 4, 5])

359

sample = rng.choice(data, size=3, replace=False) # Random sample without replacement

360

```

361

362

### Legacy Interface Examples

363

364

```python

365

import numpy as np

366

367

# Set seed for reproducibility

368

np.random.seed(42)

369

370

# Basic random generation

371

random_array = np.random.random(10) # 10 random floats [0, 1)

372

int_array = np.random.randint(1, 100, 5) # 5 random integers [1, 100)

373

374

# Distribution sampling

375

normal_data = np.random.normal(50, 15, 1000) # Mean=50, std=15

376

exponential_data = np.random.exponential(2, 500) # Scale=2

377

378

# Random sampling and permutation

379

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

380

shuffled = np.random.permutation(original) # Random permutation

381

random_choice = np.random.choice(original, 3) # Random sample with replacement

382

```

383

384

### Custom BitGenerator Usage

385

386

```python

387

import numpy as np

388

389

# Use specific BitGenerator

390

pcg = np.random.PCG64(seed=12345)

391

rng = np.random.Generator(pcg)

392

393

# Generate samples

394

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

395

396

# Multiple independent streams

397

seeds = np.random.SeedSequence(entropy=42).spawn(4)

398

generators = [np.random.Generator(np.random.PCG64(s)) for s in seeds]

399

400

# Each generator produces independent sequences

401

results = [gen.random(100) for gen in generators]

402

```