# Random number between (0,2) evenly distributed

I want to generate random numbers between `(0,2)`

. I am using the following code:

``````double fRand(double fMin, double fMax)
{
double f = (double)rand() / RAND_MAX;
return fMin + f * (fMax - fMin);
}
```

```

and installation:

``````fMin = 0; fMax = 2;
```

```

But I am not getting evenly spaced numbers. I am calling this function in a loop.

It generates random numbers, but almost all of the numbers only fall in two unevenly distributed areas.

How to ensure an even distribution of numbers?

+3

source to share

There are two ways to do this.

you can use rand, but your results will be slightly biased.

What `rand()`

does:

``````Returns a pseudo-random integral number in the range between 0 and RAND_MAX.
```

```

Example:

``````RandomFunction = rand() % 100;      // declares a random number between 0-99

RandomFunction2 = rand() % 100 + 1; // declares a random number between 1-100

This is in the library #include <cstdlib>
```

```

You can also set the seed with

``````srand()
```

```

In this case, the value of the random numbers is set, which will be the same if the function is repeated with the same value for `srand()`

. This is sometimes preferred when debugging as it makes the result clear.

Also here is a function to find unbiased values

``````std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 10);

//This function creates a random number between 1-10 and is stored in dis(gen).
// You can change the name of dis if you like.
```

```

Example:

``````#include <random>
#include <iostream>

int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);

for (int n=0; n<10; ++n)
std::cout << dis(gen) << ' ';
std::cout << '\n';
}
```

```

This will generate `10`

random numbers in between `1-6`

. Reference example: cppreference

+2

source

All Articles