Created
August 29, 2021 12:33
-
-
Save alwynallan/bc1620c9bd87b2a186d7e6dd7e05965f to your computer and use it in GitHub Desktop.
Solution per tstanisl at https://stackoverflow.com/a/68959383/5660198
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdint.h> | |
int compare (const void * a, const void * b) | |
{ | |
if (*(double*)a > *(double*)b) return 1; | |
else if (*(double*)a < *(double*)b) return -1; | |
else return 0; | |
} | |
double grand_f_0_1(){ | |
static FILE * fp = NULL; | |
uint64_t bits; | |
if(fp == NULL) fp = fopen("/dev/urandom", "r"); | |
fread(&bits, sizeof(bits), 1, fp); | |
return (double)bits * 5.421010862427522170037264004349e-020; // https://stackoverflow.com/a/26867455 | |
} | |
int main() | |
{ | |
const int n = 10; | |
double values[n]; | |
double diffs[n]; | |
double shift; | |
int i, j; | |
for(j=0; j<1000000; j++) { | |
values[0] = 0.; // https://stackoverflow.com/a/68959383/5660198 | |
for(i=1; i<n; i++) values[i] = grand_f_0_1(); | |
qsort(values+1, n-1, sizeof(double), compare); | |
shift = grand_f_0_1(); | |
for(i=0; i<n; i++) { | |
values[i] += shift; | |
if(values[i] >= 1.) values[i] -= 1.; | |
} | |
// cannot resort here! | |
for(i=0; i<n; i++) { | |
diffs[i] = values[(i+1)%n] - values[i]; | |
if(diffs[i] < 0.) diffs[i] += 1.; | |
} | |
for(i=0; i<n; i++) printf("%.5f%s", diffs[i], i<(n-1)?"\t":"\n"); | |
} | |
return(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment