Overview
Random sampling functions allow you to randomly select elements from populations, shuffle arrays, and generate permutations.Functions
choice
Random sample from array.Input array or integer (if integer, sample from arange(a))
Number of samples or output shape (default: 1)
Whether to sample with replacement (default: true)
Optional probability weights for weighted sampling
Tensor of randomly selected elements
- Input tensor must be contiguous (no slicing/striding)
- With replacement: can sample more elements than population size
- Without replacement: size must be ≤ population size
- Does NOT modify the input tensor (returns a new tensor)
- If
ais a number, the population is0..a-1and output dtype is int32
shuffle
Randomly shuffle array in-place.Input tensor (MODIFIED IN-PLACE)
- Uses Fisher-Yates shuffle algorithm (O(n) time, optimal)
- Input tensor must be contiguous (no slicing/striding)
- All elements are preserved, only their order changes
- Deterministic when seed is set via
setSeed() - If you need a shuffled copy without mutation, use
permutation()instead
permutation
Return random permutation of array.Input tensor or integer
New tensor with shuffled values
- Returns a NEW tensor (does NOT modify input)
- If x is an integer, returns permutation of arange(x)
- If x is a tensor, returns a shuffled copy with the same shape
- Tensor inputs must be contiguous (no slicing/striding)
- Uses Fisher-Yates shuffle algorithm internally
- Deterministic when seed is set via
setSeed() - Numeric input is limited to
x <= 2^31for int32 output
Seed Management
All sampling functions respect the global random seed. UsesetSeed(), getSeed(), and clearSeed() from the distributions module to control randomness.
Example: