Created
October 10, 2016 09:55
-
-
Save antirez/1677782413c0014832d12db76778215b to your computer and use it in GitHub Desktop.
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
/* 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; | |
} |
Author
antirez
commented
Oct 10, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment