Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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