Creates a tensor with the given shape, filled with random values from a uniform distribution over the interval `[0, 1)`. You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor. ```python exec="true" source="above" session="tensor" resu
(*shape, device:str|None=None, dtype:DTypeLike|None=None, contiguous:bool=True)
| 565 | |
| 566 | @staticmethod |
| 567 | def rand(*shape, device:str|None=None, dtype:DTypeLike|None=None, contiguous:bool=True) -> Tensor: |
| 568 | """ |
| 569 | Creates a tensor with the given shape, filled with random values from a uniform distribution over the interval `[0, 1)`. |
| 570 | |
| 571 | You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor. |
| 572 | |
| 573 | ```python exec="true" source="above" session="tensor" result="python" |
| 574 | Tensor.manual_seed(42) |
| 575 | t = Tensor.rand(2, 3) |
| 576 | print(t.numpy()) |
| 577 | ``` |
| 578 | """ |
| 579 | dt = to_dtype(dtype or dtypes.default_float) |
| 580 | if not dtypes.is_float(dt): raise ValueError(f"rand only supports float dtypes, got {dt}") |
| 581 | if not all_int(shape:=argfix(*shape)) or not all(s >= 0 for s in shape): raise ValueError(f"invalid input {shape=}") |
| 582 | if device is not None and not isinstance(device, str): raise ValueError(f"rand only supports single device, got {device=}") |
| 583 | device = cast(str, canonicalize_device(device)) |
| 584 | |
| 585 | # if shape has 0, return zero tensor |
| 586 | if (numel := prod(shape)) == 0: return Tensor.zeros(shape, device=device, dtype=dt) |
| 587 | num = ceildiv(numel * dt.itemsize, 4) |
| 588 | key, counter = Tensor._next_counter(device, num) |
| 589 | bits = Tensor.random_bits(key, counter, num) |
| 590 | out = Tensor._bits_to_rand(bits, shape, dt) |
| 591 | return out.contiguous() if contiguous else out |
| 592 | |
| 593 | # ***** creation helper functions ***** |
| 594 |