0

How do you create a random double between .1 and 2.5?

This is what I have been trying.

srand(time(NULL));

((double) rand() / RAND_MAX) * 2.5 + .1
jax
  • 19
  • 3

1 Answers1

4

The modern way is to use a random number distribution:

#include <iostream>
#include <random>

using namespace std;

int main()
{
    random_device rd;
    mt19937_64 generator(rd());
    uniform_real_distribution<double> distribution(0.1, 2.5);
    for (int i = 0; i < 10; i++)
    {
        double d = distribution(generator);
        cout << d << endl;
    }
    return 0;
}

Note that 0.1 <= d < 2.5.

Sid S
  • 6,037
  • 2
  • 18
  • 24
  • 2
    Yeah, use `std::rand` is really a bad practice. – con ko May 01 '18 at 03:10
  • I can't go that far. It depends too much on what you need that random number for. If you need quick and don't mind dirty, don't use a more expensive option. – user4581301 May 01 '18 at 03:17
  • Two suggestions - 1) use `random_device` for the seed. 2) instead of `default_random_engine` which you don't know what will be (and could be as bad as `rand`), use `mt19937`. – Jesper Juhl May 01 '18 at 03:28
  • 1
    A warning about `random_device`: The C++ Standard allows it to be implemented a little too simplistically. Make sure that your tool chain's library implementation is actually generating random sequences with a couple tests. – user4581301 May 01 '18 at 03:35
  • Seeding with a single call to `std::random_device` is actually pretty bad, but there isn't a quick and easy solution. In some cases, `std::random_device` is another prng with fixed seed – Passer By May 01 '18 at 07:09