Created
November 10, 2011 12:02
-
-
Save DRMacIver/1354700 to your computer and use it in GitHub Desktop.
Generate random points on a 10-sphere
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 <stdlib.h> | |
#include <stdio.h> | |
#include <time.h> | |
#include <unistd.h> | |
#include <math.h> | |
double random_uniform(){ | |
return ((double)rand()) / ((double)RAND_MAX); | |
} | |
double random_normal(){ | |
double u, v, s; | |
do{ | |
u = 2 * random_uniform() - 1; | |
v = 2 * random_uniform() - 1; | |
s = u * u + v * v; | |
} while(s >= 1); | |
return u * sqrt(-2 * log(s) / s); | |
} | |
void random_sphere(int n, double *data){ | |
double tot = 0; | |
for(int i = 0; i < n; i++){ | |
double x = random_normal(); | |
tot += x * x; | |
data[i] = x; | |
} | |
double norm = sqrt(tot); | |
for(int i = 0; i < n; i++){ | |
data[i] /= norm; | |
} | |
} | |
#define DIM 10 | |
int main(){ | |
double coords[DIM]; | |
srand(time(NULL) ^ getpid()); | |
random_sphere(DIM, coords); | |
for(int i = 0; i < DIM; i++){ | |
printf("%G", coords[i]); | |
if (i == DIM - 1){ | |
printf("\n"); | |
} else { | |
printf(" "); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment