More thoughts on random floats
I was reading this interesting thread about generating random ranges of floating point values.
What about closed ranges? I was wondering if a simple binary partitioning approach could be used.
Code:
#include "stdbool.h"
double random_within_range_with(bool (*extract_bit)(void*), void* data, double low, double high)
{
if(low > high)
return random_within_range_with(extract_bit, data, high, low);
double range = (high - low) / 2;
double sum = range;
for(;;)
{
range /= 2;
if(extract_bit(data))
sum += range;
else
sum -= range;
if(range == 0)
break;
}
return low + sum;
}
#include "stdlib.h"
#include "time.h"
bool extract_srand_bit(void* unused)
{
static bool init = true;
if(init)
{
srand(time(NULL));
init = false;
}
return rand() & 1;
}
double random_within_range(double low, double high)
{
return random_within_range_with(extract_srand_bit, NULL, low, high);
}
#include "stdio.h"
int main(int argc, char** argv)
{
puts("Random [LOW] [HIGH]");
double low = -1;
if(argc > 1)
low = atof(argv[1]);
double high = 1;
if(argc > 2)
high = atof(argv[2]);
printf("Low: %g\n", low);
printf("High: %g\n", high);
for(;;)
{
printf(" %g\n", random_within_range(low, high));
getchar();
}
}
I'm trying to avoid platform-specific particularities. Does that look like an acceptable approach?