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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With