You can sow over time (once before all calls before rand ) as follows:
#include <time.h> // ... srand (time ( NULL));
With this function you can set min / max as needed.
#include <stdio.h> #include <stdlib.h> /* generate a random floating point number from min to max */ double randfrom(double min, double max) { double range = (max - min); double div = RAND_MAX / range; return min + (rand() / div); }
Source: [SOLVED] Random dual-generator problem (C programming) in Ubuntu Forums
Then you would call it like this:
double myRand = randfrom(-1.0, 1.0);
Note, however, that this will most likely not cover the entire range of precision available with double . Excluding the exponent, the IEEE-754 double contains 52 bits of significance (i.e., the non-exponential part). Since rand returns an int between 0 and RAND_MAX , the maximum possible value of RAND_MAX is INT_MAX . On many (most?) Platforms, int is 32 bits, so INT_MAX is 0x7fffffff , covering 31 bits of the range.
source share