Generate a random double between -1 and 1

This will seed the random number generator and give a double in the range of -1.0 to 1.0

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    double random_value;

    srand ( time ( NULL));

    random_value = (double)rand()/RAND_MAX*2.0-1.0;//float in range -1 to 1

    printf ( "%f\n", random_value);

    return 0;
}

You can seed with time (once before all calls to rand) like this:

#include <time.h>

// ...
srand (time ( NULL));

With this function you can set the 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 double generator problem (C Programming) at Ubuntu Forums

Then you would call it like this:

double myRand = randfrom(-1.0, 1.0);

Note, however, that this most likely won't cover the full range of precision available from a double. Without even considering the exponent, an IEEE-754 double contains 52 bits of significand (i.e. the non-exponent 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 range.

Tags:

C