Should rand() return a RAND_MAX value for 32 bit target?

Jonathan Wakely jwakely.gcc@gmail.com
Tue Sep 18 13:49:00 GMT 2018


On Tue, 18 Sep 2018 at 14:09, Xi Ruoyao wrote:
>
> On 2018-09-18 17:52 +0530, Neha Gowda wrote:
> > Hi,
> >
> > I am trying to run the following testcase for Random Number Generator
> > function.
> > The testcase returns true when generated number is RAND_MAX and returns
> > false when its not generated.
> >
> > Command :- gcc -m32 -O2 test.c
> > ======================================================
> > #include <stdio.h>
> > #include <stdlib.h>
> >
> > int main()
> > {
> >     unsigned int i;
> >     float f;
> >     srand(0);
> >     for (i = 0; i <= RAND_MAX; i++) {
> >         f = rand();
>
> There is a rounding error introduced since a float can not represent
> all integer values in [0, RAND_MAX].
>
> >         if (f == RAND_MAX) {
>
> RAND_MAX is 2147483647 on 32-bit GNU/Linux.  It can not be represented
> by a float.

Which leads to the question, why are you using float anyway?

rand() returns an int, not a float.



More information about the Gcc-help mailing list