Skip to content
Advertisement

How to get a uniform distribution in a range [r1,r2] in PyTorch?

I want to get a 2-D torch.Tensor with size [a,b] filled with values from a uniform distribution (in range [r1,r2]) in PyTorch.

Advertisement

Answer

If U is a random variable uniformly distributed on [0, 1], then (r1 - r2) * U + r2 is uniformly distributed on [r1, r2].

Thus, you just need:

JavaScript

Alternatively, you can simply use:

JavaScript

To fully explain this formulation, let’s look at some concrete numbers:

JavaScript

We can break down the expression (r1 - r2) * torch.rand(a, b) + r2 as follows:

  1. torch.rand(a, b) produces an a x b (1×7) tensor with numbers uniformly distributed in the range [0.0, 1.0).
JavaScript
  1. (r1 - r2) * torch.rand(a, b) produces numbers distributed in the uniform range [0.0, -3.0)
JavaScript
  1. (r1 - r2) * torch.rand(a, b) + r2 produces numbers in the uniform range [5.0, 2.0)
JavaScript

Now, let’s break down the answer suggested by @Jonasson: (r2 - r1) * torch.rand(a, b) + r1

  1. Again, torch.rand(a, b) produces (1×7) numbers uniformly distributed in the range [0.0, 1.0).
JavaScript
  1. (r2 - r1) * torch.rand(a, b) produces numbers uniformly distributed in the range [0.0, 3.0).
JavaScript
  1. (r2 - r1) * torch.rand(a, b) + r1 produces numbers uniformly distributed in the range [2.0, 5.0)
JavaScript

In summary, (r1 - r2) * torch.rand(a, b) + r2 produces numbers in the range [r2, r1), while (r2 - r1) * torch.rand(a, b) + r1 produces numbers in the range [r1, r2).

Advertisement