Reputation: 319
why does the following c code produce real numbers only ranging between 0 and 1(eg: 0.840188,0.394383...etc) for double a,b
when the value for RAND_MAX appears to be 0.000000
. Shouldn't RAND_MAX
set the maximum value for the number generated by rand()
function ?
#include <stdio.h>
#include <stdlib.h>
int main()
{
double a,b,c;
for (int i=0;i<100;i++){
a=(double)rand()/(double)RAND_MAX;
b=(double)rand()/(double)RAND_MAX;
c=a-b;
printf("itteration : %d values a=%f,b=%f,c=%f, RAND_MAX=%f \n",i,a,b,c,RAND_MAX);
}
return 0;
}
Upvotes: 4
Views: 40616
Reputation: 23
RAND_MAX is an integer and when you print it with %f, in binary it is truncated. In actual , 0 is what the last several number of RAND_MAX in binary show you in decimal
Upvotes: 0
Reputation: 26800
...the value for RAND_MAX appears to be 0.000000.
You are printing an integer using the specifier for a double. This is undefined behaviour.
From the C99 standard (N1256).
7.19.6.3 The printf function
...
2. The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.7.19.6.1 The fprintf function
....
9. If a conversion specification is invalid, the behaviour is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
So it prints 0.000
for RAND_MAX
. Your other question:
Shouldn't RAND_MAX set the maximum value for the number generated by rand() function ?
rand()
returns a pseudo-random number in the range of 0
to RAND_MAX
.
RAND_MAX
is a constant whose default value may vary between implementations but it is granted to be at least 32767
.
But floating point division of rand()
with RAND_MAX
will yield a value between 0
and 1
.
Upvotes: 1
Reputation: 126837
RAND_MAX
is an integral constant, but you are printing it using the %f
specifier (used for double
), which is undefined behavior (and in your case happens to print 0). Use %d
and you'll see the actual value of RAND_MAX
.
By the way, pretty much any decent compiler will warn you about that invalid printf
if you crank the warnings high enough. Make sure to do so, C and C++ are full of traps enough, at least let the compiler help you when it can.
Upvotes: 10