Is there anything similar to NumPy `random.randint`

to generate random integers between a certain range?

3 Likes

`torch.rand`

outputs a tensor fill out with random numbers within `[0,1)`

. You can use that and convert it to the range `[l,r)`

using a formula like `l + torch.rand() * (r - l)`

and then converting them to integers as usual.

3 Likes

You could also directly set the range using:

```
torch.LongTensor(10).random_(0, 10)
```

where numbers define the lower and upper bound, respectively.

25 Likes

PyTorch also supports randint: https://pytorch.org/docs/stable/torch.html#torch.randint

```
torch.randint(3, 5, (3,))
tensor([ 4., 3., 4.])
```

13 Likes

this should work:

```
import torch
batch_size = 16
y = torch.randint(low=0,high=Dout,size=(batch_size,))
```

docs: https://pytorch.org/docs/stable/generated/torch.randint.html#torch.randint