Reputation: 275
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
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
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
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
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
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