Skip to content

Instantly share code, notes, and snippets.

@DRMacIver
Created November 10, 2011 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DRMacIver/1354700 to your computer and use it in GitHub Desktop.
Save DRMacIver/1354700 to your computer and use it in GitHub Desktop.
Generate random points on a 10-sphere
#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