problem with using double and drand48

Ted Powell ted at eslvcr.wimsey.bc.ca
Sun Oct 7 08:55:10 AEST 1990


In article <279 at geocub.greco-prog.fr> lath at geocub.greco-prog.fr (Laurent Lathieyre) writes:
>
>here a piece of C code which provides some strange
>results :
>double d;
>printf("%f\n",drand(48));
>d=drand48();
>printf("%f\n",d);
>
>output:
>0.899854
>1071863078.000000
>
>according to the manual section 3, drand48() is supposed to return a
>double type value in [0.0,1.0]...

This is exactly why you get absurd results if you let the type default
to int. The function returns a double, probably in a floating point
register, and your program's generated code picks up garbage from
wherever integer results are normally returned.

To tell the compiler that drand48 returns a double value, you need a line
like:
    double drand48();
otherwise the C compiler will helpfully (hah!) default the type to int.
Some library functions will have an associated header file that contains
a declaration of the function. Since this function doesn't, one needs
to determine the necessary declaration from the SYNOPSIS section of the
man page.

drand(48) above should be drand48() -- when posting code, it's generally 
best to extract it from the file you actually compiled and ran. 

The returned range is [0.0, 1.0), not [0.0, 1.0] -- i.e. you are guaranteed
not to get the value 1.0 returned.
-- 
ted at eslvcr.wimsey.bc.ca   ...!ubc-cs!van-bc!eslvcr!ted    (Ted Powell)



More information about the Comp.sys.att mailing list