Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random number between 0 and 1?

Tags:

c

I want to generate random numbers between (0,1). I am trying the following:

double r2()
{
    return((rand() % 10000) / 10000.0);
}

int SA()
{
    double u;
    u = r2();
}

But it doesn't generate the expected result. How can I fix it?

like image 564
user739062 Avatar asked Jun 02 '11 18:06

user739062


People also ask

How will you get a random number between 0 and 1 in?

Using the random.uniform() function is perfectly suited to generate a random number between the numbers 0 and 1, as it is utilized to return a random floating-point number between two given numbers specified as the parameters for the function.

How do you randomly assign 0 to 1 in Excel?

The Excel RAND function returns a random number between 0 and 1. For example, =RAND() will generate a number like 0.422245717. RAND recalculates when a worksheet is opened or changed. The RAND function returns a random decimal number between 0 and 1.

How do you generate a random number from 0 to 1 in Python?

Numbers generated with this module are not truly random but they are enough random for most purposes. Random number between 0 and 1. print(random()) # Generate a pseudo-random number between 0 and 1. print(randint(1, 100)) # Pick a random number between 1 and 100.

How do you get a random number between 0 and 1 in C ++?

Using the rand() function to generate random number between 0 and 1 in C++ The rand() function is used to generate a random number in C++.


3 Answers

In your version rand() % 10000 will yield an integer between 0 and 9999. Since RAND_MAX may be as little as 32767, and since this is not exactly divisible by 10000 and not large relative to 10000, there will be significant bias in the 'randomness' of the result, moreover, the maximum value will be 0.9999, not 1.0, and you have unnecessarily restricted your values to four decimal places.

It is simple arithmetic, a random number divided by the maximum possible random number will yield a number from 0 to 1 inclusive, while utilising the full resolution and distribution of the RNG

double r2() {     return (double)rand() / (double)RAND_MAX ; } 

Use (double)rand() / (double)((unsigned)RAND_MAX + 1) if exclusion of 1.0 was intentional.

like image 114
Clifford Avatar answered Sep 30 '22 18:09

Clifford


Here's a general procedure for producing a random number in a specified range:

int randInRange(int min, int max) {   return min + (int) (rand() / (double) (RAND_MAX + 1) * (max - min + 1)); } 

Depending on the PRNG algorithm being used, the % operator may result in a very non-random sequence of numbers.

like image 30
John Bode Avatar answered Sep 30 '22 18:09

John Bode


It seems to me you have not called srand first. Usage example here.

like image 41
andreea Avatar answered Sep 30 '22 16:09

andreea