nullpointer
nullpointer

Reputation: 275

Get random double number from [0,1] in C++

I want to generate random double number x, where: 0 <= x <= 1:

double x = ((double) rand() / (RAND_MAX));

Is this the correct way of getting random double number from [0,1] ?

Upvotes: 6

Views: 33644

Answers (5)

Genesis
Genesis

Reputation: 159

If you were looking for a random double this is how I achieved it.

If you are looking for it in a function I can edit this post.

rand() is included within stdlib.h

    #include <stdlib.h>
    #include <time.h>
    #include <iostream>
    using namespace std;
    int main()
    { 
        double num;
        double max;

        srand(time(NULL));

        cout << "Enter a number.";
        cin >> max;

        num = (((double)rand()*(max) / RAND_MAX) - max) *(-1);

        cout << num;


    }

Upvotes: 1

Aayush Gupta
Aayush Gupta

Reputation: 93

Yep, I believe it will give you 0 and 1 in a random sequence when generated subsequently. But be sure to initialize the random number generator function to avoid getting same sequence again and again.

Upvotes: 2

Mauro H. Leggieri
Mauro H. Leggieri

Reputation: 1104

Yes but I recommend to cast RAND_MAX to double too:

double r = ((double)rand() / (double)(RAND_MAX));

Although sometimes unnecessary, the compiler may automatically cast operators to another type depending on target and source variable types. For e.g:

3.5 / 2 may be equal to 1 and not 1.75 because the divisor is an integer and to avoid this you must do:

3.5 / 2.0 or 3.5 / (double)2

Upvotes: 1

Joachim W
Joachim W

Reputation: 8167

Yes.

Some parentheses are superfluous though.

And it depends on your application whether you can trust your systems rand(3) function. For serious Monte-Carlo simulations you will need a well-documented random-number generator from a numerical library.

Upvotes: 3

Zeta
Zeta

Reputation: 105885

Yes, since std::rand() returns both 0 and RAND_MAX. However, if you can use C++11, you can use std::uniform_real_distribution instead.

Also don't forget to initialize your random number generator, otherwise you will get the same sequence in every execution. If you use std::rand, std::srand( std::time(0) ) is almost always sufficient.

Upvotes: 9

Related Questions