0
# Random Number Generation
1
2
GPU-based random number generation with comprehensive probability distributions. CuPy provides both legacy RandomState interface and modern Generator API with various bit generators, all accelerated on GPU for high-performance random sampling.
3
4
## Capabilities
5
6
### Generator API (Recommended)
7
8
Modern random number generation interface with explicit state management and multiple bit generators.
9
10
```python { .api }
11
def default_rng(seed=None):
12
"""
13
Construct default random number generator.
14
15
Parameters:
16
- seed: int, array-like, SeedSequence, BitGenerator, or Generator, optional
17
18
Returns:
19
cupy.random.Generator: Random number generator instance
20
"""
21
22
class Generator:
23
"""
24
Random number generator with explicit state management.
25
26
Modern interface for random number generation providing
27
better control over random state and reproducibility.
28
"""
29
30
def __init__(self, bit_generator):
31
"""
32
Initialize generator with bit generator.
33
34
Parameters:
35
- bit_generator: cupy.random.BitGenerator, source of randomness
36
"""
37
38
def random(self, size=None, dtype=cupy.float64, out=None):
39
"""
40
Generate random floats in [0.0, 1.0).
41
42
Parameters:
43
- size: int or tuple, output shape, optional
44
- dtype: data type, float32 or float64
45
- out: array, output array, optional
46
47
Returns:
48
cupy.ndarray: Random floats on GPU
49
"""
50
51
def integers(self, low, high=None, size=None, dtype=cupy.int64):
52
"""
53
Generate random integers.
54
55
Parameters:
56
- low: int, lower bound (inclusive) or upper bound if high is None
57
- high: int, upper bound (exclusive), optional
58
- size: int or tuple, output shape, optional
59
- dtype: data type, integer type
60
61
Returns:
62
cupy.ndarray: Random integers on GPU
63
"""
64
65
def normal(self, loc=0.0, scale=1.0, size=None):
66
"""
67
Generate normally distributed random numbers.
68
69
Parameters:
70
- loc: float or array, mean
71
- scale: float or array, standard deviation
72
- size: int or tuple, output shape, optional
73
74
Returns:
75
cupy.ndarray: Normal random numbers on GPU
76
"""
77
78
def uniform(self, low=0.0, high=1.0, size=None):
79
"""
80
Generate uniformly distributed random numbers.
81
82
Parameters:
83
- low: float or array, lower bound
84
- high: float or array, upper bound
85
- size: int or tuple, output shape, optional
86
87
Returns:
88
cupy.ndarray: Uniform random numbers on GPU
89
"""
90
91
class BitGenerator:
92
"""
93
Base class for bit generators.
94
95
Provides the core random bit generation functionality
96
used by Generator instances.
97
"""
98
99
def random_raw(self, size=None, output=True):
100
"""
101
Generate raw random bits.
102
103
Parameters:
104
- size: int or tuple, output shape, optional
105
- output: bool, whether to return output
106
107
Returns:
108
cupy.ndarray: Raw random bits
109
"""
110
111
class XORWOW(BitGenerator):
112
"""
113
XORWOW bit generator (default for CuPy).
114
115
Fast bit generator suitable for most applications,
116
optimized for GPU parallel execution.
117
"""
118
119
def __init__(self, seed=None):
120
"""
121
Initialize XORWOW bit generator.
122
123
Parameters:
124
- seed: int, array-like, or SeedSequence, optional
125
"""
126
```
127
128
### Simple Random Data Functions
129
130
Convenient functions for common random number generation tasks.
131
132
```python { .api }
133
def random(size=None):
134
"""
135
Generate random floats in [0.0, 1.0).
136
137
Parameters:
138
- size: int or tuple, output shape, optional
139
140
Returns:
141
cupy.ndarray: Random floats on GPU
142
"""
143
144
def rand(*size):
145
"""
146
Generate random floats in [0.0, 1.0) with specified dimensions.
147
148
Parameters:
149
- size: ints, dimensions
150
151
Returns:
152
cupy.ndarray: Random floats on GPU
153
"""
154
155
def randn(*size):
156
"""
157
Generate standard normal random numbers.
158
159
Parameters:
160
- size: ints, dimensions
161
162
Returns:
163
cupy.ndarray: Standard normal random numbers on GPU
164
"""
165
166
def randint(low, high=None, size=None, dtype=int):
167
"""
168
Generate random integers.
169
170
Parameters:
171
- low: int, lower bound (inclusive) or upper bound if high is None
172
- high: int, upper bound (exclusive), optional
173
- size: int or tuple, output shape, optional
174
- dtype: data type, integer type
175
176
Returns:
177
cupy.ndarray: Random integers on GPU
178
"""
179
180
def choice(a, size=None, replace=True, p=None):
181
"""
182
Generate random sample from array.
183
184
Parameters:
185
- a: int or array-like, input array or size
186
- size: int or tuple, output shape, optional
187
- replace: bool, sampling with replacement
188
- p: array-like, probabilities, optional
189
190
Returns:
191
cupy.ndarray: Random sample on GPU
192
"""
193
```
194
195
### Probability Distributions
196
197
Comprehensive set of probability distributions for statistical sampling.
198
199
```python { .api }
200
def normal(loc=0.0, scale=1.0, size=None):
201
"""
202
Normal (Gaussian) distribution.
203
204
Parameters:
205
- loc: float or array, mean
206
- scale: float or array, standard deviation
207
- size: int or tuple, output shape, optional
208
209
Returns:
210
cupy.ndarray: Normal random numbers on GPU
211
"""
212
213
def uniform(low=0.0, high=1.0, size=None):
214
"""
215
Uniform distribution.
216
217
Parameters:
218
- low: float or array, lower bound
219
- high: float or array, upper bound
220
- size: int or tuple, output shape, optional
221
222
Returns:
223
cupy.ndarray: Uniform random numbers on GPU
224
"""
225
226
def exponential(scale=1.0, size=None):
227
"""
228
Exponential distribution.
229
230
Parameters:
231
- scale: float or array, scale parameter
232
- size: int or tuple, output shape, optional
233
234
Returns:
235
cupy.ndarray: Exponential random numbers on GPU
236
"""
237
238
def gamma(shape, scale=1.0, size=None):
239
"""
240
Gamma distribution.
241
242
Parameters:
243
- shape: float or array, shape parameter
244
- scale: float or array, scale parameter
245
- size: int or tuple, output shape, optional
246
247
Returns:
248
cupy.ndarray: Gamma random numbers on GPU
249
"""
250
251
def beta(a, b, size=None):
252
"""
253
Beta distribution.
254
255
Parameters:
256
- a: float or array, alpha parameter
257
- b: float or array, beta parameter
258
- size: int or tuple, output shape, optional
259
260
Returns:
261
cupy.ndarray: Beta random numbers on GPU
262
"""
263
264
def binomial(n, p, size=None):
265
"""
266
Binomial distribution.
267
268
Parameters:
269
- n: int or array, number of trials
270
- p: float or array, probability of success
271
- size: int or tuple, output shape, optional
272
273
Returns:
274
cupy.ndarray: Binomial random numbers on GPU
275
"""
276
277
def poisson(lam=1.0, size=None):
278
"""
279
Poisson distribution.
280
281
Parameters:
282
- lam: float or array, rate parameter
283
- size: int or tuple, output shape, optional
284
285
Returns:
286
cupy.ndarray: Poisson random numbers on GPU
287
"""
288
289
def chisquare(df, size=None):
290
"""
291
Chi-square distribution.
292
293
Parameters:
294
- df: float or array, degrees of freedom
295
- size: int or tuple, output shape, optional
296
297
Returns:
298
cupy.ndarray: Chi-square random numbers on GPU
299
"""
300
301
def laplace(loc=0.0, scale=1.0, size=None):
302
"""
303
Laplace distribution.
304
305
Parameters:
306
- loc: float or array, location parameter
307
- scale: float or array, scale parameter
308
- size: int or tuple, output shape, optional
309
310
Returns:
311
cupy.ndarray: Laplace random numbers on GPU
312
"""
313
314
def lognormal(mean=0.0, sigma=1.0, size=None):
315
"""
316
Log-normal distribution.
317
318
Parameters:
319
- mean: float or array, mean of underlying normal
320
- sigma: float or array, standard deviation of underlying normal
321
- size: int or tuple, output shape, optional
322
323
Returns:
324
cupy.ndarray: Log-normal random numbers on GPU
325
"""
326
327
def multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8):
328
"""
329
Multivariate normal distribution.
330
331
Parameters:
332
- mean: array-like, mean vector
333
- cov: array-like, covariance matrix
334
- size: int or tuple, output shape, optional
335
- check_valid: str, covariance validation
336
- tol: float, tolerance for singular values
337
338
Returns:
339
cupy.ndarray: Multivariate normal random vectors on GPU
340
"""
341
```
342
343
### Array Permutation and Sampling
344
345
Functions for shuffling arrays and generating permutations.
346
347
```python { .api }
348
def shuffle(x):
349
"""
350
Shuffle array in-place.
351
352
Parameters:
353
- x: array-like, array to shuffle
354
"""
355
356
def permutation(x):
357
"""
358
Generate random permutation.
359
360
Parameters:
361
- x: int or array-like, array to permute or size
362
363
Returns:
364
cupy.ndarray: Random permutation on GPU
365
"""
366
```
367
368
### Random State Management (Legacy)
369
370
Legacy interface for backward compatibility with older NumPy random APIs.
371
372
```python { .api }
373
class RandomState:
374
"""
375
Random state container (legacy interface).
376
377
Maintains random state for reproducible random number generation.
378
Provided for compatibility with older NumPy random APIs.
379
"""
380
381
def __init__(self, seed=None):
382
"""
383
Initialize random state.
384
385
Parameters:
386
- seed: int, array-like, or None, random seed
387
"""
388
389
def seed(self, seed=None):
390
"""
391
Reseed random number generator.
392
393
Parameters:
394
- seed: int, array-like, or None, random seed
395
"""
396
397
def get_state(self):
398
"""
399
Get current random state.
400
401
Returns:
402
dict: Current random state
403
"""
404
405
def set_state(self, state):
406
"""
407
Set random state.
408
409
Parameters:
410
- state: dict, random state to restore
411
"""
412
413
def seed(seed=None):
414
"""
415
Seed global random number generator.
416
417
Parameters:
418
- seed: int, array-like, or None, random seed
419
"""
420
421
def get_random_state():
422
"""
423
Get global random state.
424
425
Returns:
426
cupy.random.RandomState: Global random state
427
"""
428
429
def set_random_state(state):
430
"""
431
Set global random state.
432
433
Parameters:
434
- state: cupy.random.RandomState, random state to set
435
"""
436
```
437
438
## Usage Examples
439
440
### Basic Random Number Generation
441
442
```python
443
import cupy as cp
444
445
# Simple random arrays
446
random_floats = cp.random.random((1000, 1000))
447
random_ints = cp.random.randint(0, 100, size=(500, 500))
448
normal_data = cp.random.randn(10000)
449
450
# Seeded generation for reproducibility
451
cp.random.seed(42)
452
reproducible_data = cp.random.random(1000)
453
454
cp.random.seed(42) # Same seed
455
same_data = cp.random.random(1000)
456
print(cp.allclose(reproducible_data, same_data)) # True
457
```
458
459
### Modern Generator API
460
461
```python
462
# Create generator with specific seed
463
rng = cp.random.default_rng(seed=12345)
464
465
# Generate various distributions
466
uniform_samples = rng.uniform(-1, 1, size=10000)
467
normal_samples = rng.normal(0, 1, size=10000)
468
integer_samples = rng.integers(1, 7, size=1000) # Dice rolls
469
470
# Advanced distributions
471
gamma_samples = rng.gamma(2.0, 1.0, size=5000)
472
beta_samples = rng.beta(2.0, 5.0, size=5000)
473
474
# Multiple generators with different seeds
475
rng1 = cp.random.default_rng(1234)
476
rng2 = cp.random.default_rng(5678)
477
478
data1 = rng1.normal(size=1000)
479
data2 = rng2.normal(size=1000)
480
print(f"Correlation: {cp.corrcoef(data1, data2)[0, 1]}") # Should be low
481
```
482
483
### Statistical Sampling
484
485
```python
486
# Sample from predefined array
487
population = cp.arange(1000)
488
sample = cp.random.choice(population, size=100, replace=False)
489
490
# Weighted sampling
491
weights = cp.exp(-cp.arange(100) / 10) # Exponential weights
492
weighted_sample = cp.random.choice(100, size=50, p=weights/cp.sum(weights))
493
494
# Multivariate normal sampling
495
mean = cp.array([0, 0])
496
cov = cp.array([[1, 0.5], [0.5, 1]])
497
mv_samples = cp.random.multivariate_normal(mean, cov, size=1000)
498
499
# Bootstrap sampling
500
data = cp.random.exponential(2.0, size=1000)
501
bootstrap_samples = cp.random.choice(data, size=(1000, 1000), replace=True)
502
bootstrap_means = cp.mean(bootstrap_samples, axis=1)
503
```
504
505
### Monte Carlo Simulations
506
507
```python
508
# Monte Carlo estimation of π
509
def estimate_pi(n_samples):
510
# Generate random points in unit square
511
x = cp.random.uniform(-1, 1, n_samples)
512
y = cp.random.uniform(-1, 1, n_samples)
513
514
# Count points inside unit circle
515
inside_circle = (x**2 + y**2) <= 1
516
pi_estimate = 4 * cp.mean(inside_circle)
517
return pi_estimate
518
519
pi_est = estimate_pi(1000000)
520
print(f"π estimate: {pi_est}")
521
print(f"Error: {abs(pi_est - cp.pi)}")
522
523
# Monte Carlo integration
524
def monte_carlo_integrate(func, a, b, n_samples):
525
# Sample uniform random points
526
x = cp.random.uniform(a, b, n_samples)
527
y = func(x)
528
529
# Estimate integral
530
integral = (b - a) * cp.mean(y)
531
return integral
532
533
# Integrate x^2 from 0 to 1 (analytical result: 1/3)
534
integral_est = monte_carlo_integrate(lambda x: x**2, 0, 1, 100000)
535
print(f"Integral estimate: {integral_est}")
536
print(f"Analytical result: {1/3}")
537
```
538
539
### Advanced Random Operations
540
541
```python
542
# Generate correlated random variables
543
n = 10000
544
x = cp.random.normal(size=n)
545
noise = cp.random.normal(size=n) * 0.5
546
y = 2 * x + 1 + noise # y = 2x + 1 + noise
547
548
correlation = cp.corrcoef(x, y)[0, 1]
549
print(f"Correlation coefficient: {correlation}")
550
551
# Random walk simulation
552
steps = cp.random.choice([-1, 1], size=10000)
553
walk = cp.cumsum(steps)
554
final_position = walk[-1]
555
max_excursion = cp.max(cp.abs(walk))
556
557
print(f"Final position: {final_position}")
558
print(f"Maximum excursion: {max_excursion}")
559
560
# Rejection sampling example
561
def sample_truncated_normal(mean, std, lower, upper, size):
562
samples = []
563
while len(samples) < size:
564
candidates = cp.random.normal(mean, std, size * 2)
565
valid = candidates[(candidates >= lower) & (candidates <= upper)]
566
samples.append(valid[:min(len(valid), size - len(samples))])
567
568
return cp.concatenate(samples)[:size]
569
570
truncated_samples = sample_truncated_normal(0, 1, -2, 2, 1000)
571
print(f"Sample range: [{cp.min(truncated_samples)}, {cp.max(truncated_samples)}]")
572
```
573
574
### Performance Comparison
575
576
```python
577
import time
578
579
# Compare GPU vs CPU random generation
580
size = (10000, 10000)
581
582
# GPU generation
583
start_time = time.time()
584
gpu_random = cp.random.random(size)
585
cp.cuda.Stream.null.synchronize() # Ensure completion
586
gpu_time = time.time() - start_time
587
588
# CPU generation (for comparison)
589
import numpy as np
590
start_time = time.time()
591
cpu_random = np.random.random(size)
592
cpu_time = time.time() - start_time
593
594
print(f"GPU time: {gpu_time:.4f} seconds")
595
print(f"CPU time: {cpu_time:.4f} seconds")
596
print(f"Speedup: {cpu_time/gpu_time:.2f}x")
597
```