# How to sample positive and negative integers in Pytorch

I need to sample positive and negative integers from the uniform distribution using only Pytorch functions.

I am using the function :

random_(from=0, to=None, *, generator=None)

For example :

torch.Tensor(10).random_(2,5) : produces a tensor of length 10 with integers sampled from 2 to 5
torch.Tensor(10).random_(0,5) : produces a tensor of length 10 with integers sampled from 0 to 5
torch.Tensor(10).random_(-5,5) : produces a tensor of length 10 with integers …

The last case is problematic. I get ENORMOUS values as output.

Why?

I should emphasize that I prefer using only Pytorch function only.

This is because if you use torch.Tensor(10).random_(-5, 5), this means take random numbers between the max of your datatype -5, and 5. This behavior is similar to python lists : you can do list[-5:5], meaning start 5 elements before the end, to the 5th element. I’m not sure why this is the default behavior, and it doesn’t seem to be documented.

For example, If you’re using int 32, this will select integers between 2^32 - 5, and 5.

You could use `torch.rand` or `torch.randn` and then scale / translate it by the factors you need

Exemple : `torch.rand(10) * 5` : floats between 0 and 5 (uniform distribution)

`torch.randn(10) * 5` : normal distribution centered in 0, multiplied by 5 (sigma = 5)

EDIT : I updated my answer with ClementPinard precisions for normal distributions

2 Likes

However, I’ll just add that `torch.randn(10) * 5` won’t give you floats bewteen -5 and 5, but rather a normal distribution (so for all real numbers) with a `sigma` of 5, your numbers will only get 68% chance of being inside [-5,5] (more details here)
If you want 10 floats between -5 and 5 you should call
`torch.rand(10)*10 - 5`

2 Likes

Thanks for prompt replies!

As I want integers, I will do following :

torch.Tensor(10).random_(0,10) - 5

This will generate integers between -5 and 5 following the uniform distribution.

Thanks again!

JPh