Neri-kun
Neri-kun

Reputation: 193

How can i generate random doubles in C?

I have to involve experimental data in my code by addressing a method for automated generation of non-trivial input test data.How can I do this,considering the fact that I also have to take into consideration numbers of double type?

Here's some additional context.From page 139 from this book http://mimoza.marmara.edu.tr/~msakalli/cse706_12/SkienaTheAlgorithmDesignManual.pdf which is more accurately page 151 from the PDF,I had to solve problem 4.3,which I did.However I need to generate random input for this problem,and since I have to deal with real numbers,it will most likely be needed to generate double numbers.Problem is I don't know what range I should choose for this case when generating real numbers.

Upvotes: 4

Views: 7179

Answers (4)

chux
chux

Reputation: 154169

To achieve a random double in the range of [-DBL_MAX ....DBL_MAX] with about equal chance of any double appearing, randomly populate a double. Reject non-finite ones.

#include <math.h>
#include <stdlib.h>

double rand_finite_double(void) {
  union {
    double d;
    unsigned char uc[sizeof(double)];
  } u;
  do {
    for (unsigned i = 0; i < sizeof u.uc; i++) {
      u.uc[i] = (unsigned char) rand();
    }
  } while (!isfinite(u.d));
  return u.d;
}

Somewhat linearly inefficient given only 8 bits typically generated each loop iteration.

Upvotes: 5

ryyker
ryyker

Reputation: 23236

How can i generate random doubles in C?

No bells and whistles, but will get you started:

double drand ( double low, double high )
{
    srand((unsigned int)clock());
     return ( (double)rand() * ( high - low ) ) / (double)RAND_MAX + low;
}

For low = 10.0;
and high = 1000.0
a call to this function will generate a single value:
10 >= value <= 1000.0

Adapted from this example.

Upvotes: 0

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13196

C's rand() returns an int, typically 32 bits. A double has 53 bits of mantissa. So to create a good random double you'll have to generate 53 random bits. Try something like this:

double rd() {
    uint64_t r53 = ((uint64_t)(rand()) << 21) ^ (rand() >> 2);
    return (double)r53 / 9007199254740991.0; // 2^53 - 1
}

This will return a double in the interval [0, 1]

Upvotes: 4

0___________
0___________

Reputation: 67855

for examle 0 to max:

double pseudorand(double max)
{   
    srand((unsigned) time(0));
    return (max / RAND_MAX) * rand();
}

or from -max to max

double pseudorand(double max)
{   
    srand((unsigned) time(0));
    return (rand() > RAND_MAX / 2 ? -1 : 1) *(max / RAND_MAX) * rand();
}

https://onlinegdb.com/SyqGH9PqN

Upvotes: 1

Related Questions