Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@antirez
Created October 10, 2016 09:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antirez/1677782413c0014832d12db76778215b to your computer and use it in GitHub Desktop.
Save antirez/1677782413c0014832d12db76778215b to your computer and use it in GitHub Desktop.
/* Copyright (C) 2016 Salvatore Sanfilippo. All Rights Resereved.
* This code is released under the BSD 3 clause license. */
#include <math.h>
#include <stdlib.h>
/* Return a random number with normal distribution and the specified
* mean and variance. It uses the "polar method" but does not cache one
* of the previously generated random numbers, it just returns a single
* one per iteration in order for the function to be completely stateless. */
double normrand(double mean, double variance) {
double v1, v2, s;
do {
/* Generate two uniform random numbers in the -1,1 range. */
v1 = (double)rand()/RAND_MAX * 2 - 1;
v2 = (double)rand()/RAND_MAX * 2 - 1;
s = v1*v1+v2*v2;
} while(s >= 1);
/* Obtain a number with unit normal distibution. */
v1 = sqrt(-2*log(s)/s)*v1;
/* Convert it to requested mean and variance. */
return mean + sqrt(variance) * v1;
}
#include <stdio.h>
#include <time.h>
int main(void) {
int histogram[21] = {0};
srand(time(NULL));
for (int j = 0; j < 5000; j++) {
double r = normrand(10.5,10);
int idx = r;
if (idx < 0 || idx > 20) continue;
histogram[idx]++;
}
for (int j = 0; j < 21; j++) {
for (int i = 0; i < histogram[j]/10; i++) printf("%c",'o');
printf("\n");
}
return 0;
}
@antirez
Copy link
Author

antirez commented Oct 10, 2016

$ ./a.out

o
oo
oooooo
ooooooooo
oooooooooooooooooo
ooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooo
ooooooooooooooooo
ooooooooo
oooo
oo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment