fn

rand

Tensor
rand(size: _int | tuple[_int, ...] = (), dtype: DTypeLike = None, device: DeviceLike = None, requires_grad: _bool = False, generator: _C_engine.Generator | None = None)
source

Return a tensor of samples drawn from the continuous uniform distribution.

Each element is drawn independently from U[0,1)U[0, 1), the uniform distribution on the half-open unit interval:

XiU[0,1),fX(x)={10x<10otherwiseX_i \sim U[0, 1), \quad f_X(x) = \begin{cases} 1 & 0 \le x < 1 \\ 0 & \text{otherwise} \end{cases}

The distribution has mean E[X]=12\mathbb{E}[X] = \tfrac{1}{2} and variance Var[X]=112\operatorname{Var}[X] = \tfrac{1}{12}.

Parameters

*sizeint or tuple[int, ...]
Shape of the output tensor. Accepts varargs rand(2, 3) or a single tuple rand((2, 3)).
dtypelucid.dtype
Floating-point data type. Defaults to the global default (lucid.float32). Integer dtypes are not supported.
devicestr or lucid.device
Target device — "cpu" or "metal".
requires_gradbool
If True, downstream operations are tracked by autograd. Default: False.
generatorlucid._C.engine.Generator
Explicit generator to use. When None (default), the global default generator is used.

Returns

Tensor

Tensor of shape size with values in [0,1)[0, 1).

Notes

Internally the engine applies the Philox bijection and converts the raw 32-bit output to a float via the standard IEEE 754 mantissa trick:

x=(u  &  0x007FFFFF)    0x3F800000  (reinterpreted as float32)    1.0\begin{aligned} x = (u \;\&\; \texttt{0x007FFFFF}) \;\big|\; \texttt{0x3F800000} \;\text{(reinterpreted as float32)} \;-\; 1.0 \end{aligned}

yielding 2232^{23} equally spaced values in [0,1)[0, 1) with spacing 2231.19×1072^{-23} \approx 1.19 \times 10^{-7}.

Examples

>>> import lucid
>>> lucid.manual_seed(0)
>>> x = lucid.rand(3, 4)
>>> x.shape
(3, 4)
>>> float(x.min()) >= 0.0 and float(x.max()) < 1.0
True
Monte-Carlo estimate of $\pi$:
>>> lucid.manual_seed(0)
>>> n = 1_000_000
>>> pts = lucid.rand(n, 2)
>>> inside = ((pts ** 2).sum(dim=-1) < 1.0).float().mean()
>>> float(inside) * 4   # ≈ 3.1416