Skip to main content

Mojo function

rand

rand[dtype: DType](ptr: UnsafePointer[Scalar[dtype], ptr.origin, address_space=ptr.address_space], size: Int, /, *, min: Float64 = 0, max: Float64 = 1, int_scale: Optional[Int] = None)

Fills memory with random values from a uniform distribution.

Behavior depends on the dtype:

  • Floating-point types sample values uniformly from [min, max).
  • Integral types sample values uniformly from [min, max], clamped to the representable range of the dtype.

Example:

from std.random import rand, seed
from std.memory import alloc

seed()
var size: Int = 10
var ptr = alloc[Float32](size)
rand[DType.float32](ptr, size, min=0.0, max=1.0, int_scale=16)
for i in range(size):
    print(ptr[i])  # Random Float32 between 0.0 and 1.0
ptr.free()

Parameters:

  • dtype (DType): The dtype of the pointer.

Args:

  • ptr (UnsafePointer): The pointer to the memory area to fill.
  • size (Int): The number of elements to fill.
  • min (Float64): The lower bound of the range.
  • max (Float64): The upper bound of the range.
  • int_scale (Optional): Optional quantization scale for floating-point types. When provided, values are quantized to increments of 2^(-int_scale).

Was this page helpful?