0

I'm now working on pset4 in edx. The spec requires that the velocity of the ball to be generated from a random number using drand48().

I looked at man drand48() saying this is a double type stuff, then i tried:

double x = drand48();

then an error of implicit declaration of function 'drand48()' is invalid in c99 appeared...

I tried looking out for other options on web... E.g.:

srand(time(NULL));
int r = rand();

But the code does not generate numbers between 0 & 1... What should I do?

3

In order to use the function drand48() you need to:

#define _XOPEN_SOURCE    /* ALWAYS BEFORE the include statement */
#include <stdlib.h>

(you don't need to worry about linking, since these standard libraries get "automagically" linked by your compiler)


If what you need is to generate numbers in the range [0, 1) you should try drand48(), which does exactly that.

On the other hand, if (for whatever reason) you need/want to use rand(), you'll get numbers in the range [0, RAND_MAX], where RAND_MAX is a predefined constant, usually of value:

RAND_MAX = 32767

So... How could you turn this into a number in the range [0, 1]? You could think of it as a scaling procedure: both ranges start at 0, but they span over different "amount" of numbers. I.e.:

drand48() = [0 - - - - 1]
rand()    = [0 - - - - - - -  - - - - - - - - - - - - - - - - - - - RAND_MAX]

How would you "scale" down rand() range to [0, 1]? Think what would happen if you divided every number returned by drand48() by a factor of RAND_MAX. The range of values would then span between:

rand() = 0        -->         0 / RAND_MAX  -->  0
rand() = RAND_MAX -->  RAND_MAX / RAND_MAX  -->  1

And there it is ;)


EDIT :

According to man drand48:

The srand48(), seed48() and lcong48() functions are initialization functions, one of which should be called before using drand48(), lrand48() or mrand48().

So, unlike rand(), you need to previously seed drand48() for it to work properly:

srand48(time(0));

I sed it with time(0) so it produces different results each time. When it's time to debug, you may need to provide a "constant seed".

"man is your friend" ;)

4
  • int main(void) { double x = drand48(); printf("%f is the random number\n", x); } thanks abelinux~no more error noted, but now only 0.000 is printed, anything wrong
    – Hang Man
    Dec 30 '14 at 14:07
  • Thank you very much @abelinux!
    – Hang Man
    Dec 31 '14 at 6:56
  • if the answer proved useful, please vote it up. As per the site's conventions don't post "thank you" answers/comments ;)
    – abelinux
    Dec 31 '14 at 15:45
  • _XOPEN_SOURCE is important and will be required in pset3 breakout(2015)
    – taichouvik
    Jun 28 '16 at 20:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .