问题
I've been working on a function to generate gaussian distributed random randoms between zero and 1. This website here was a great help as I basically copied the algorithm for Polar Form to get an understanding of the procedure, but I am having trouble keeping the value between 0 and 1, including 0 but excluding 1. I believe the mathematical notation for this is [0, 1) if I'm correct. Any insight you could provide would be great. On Unix, this compiles with; gcc fileName.c -lm
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int main()
{
int i;
float x, w;
for (i=0; i<50; i++)
{
do {
x = 2.0 * ( (float)rand() / (float)RAND_MAX ) - 1.0;
w = x * x;
}while (w >= 1.0);
w = (float)sqrt( (-2.0 * log( w )) / w );
printf("%f\n", x*w);
}
return 0;
}
回答1:
I believe the questioner is asking for something like a truncated gaussian distribution. You can sample such a distribution simply by generating samples from a Gaussian distribution with mean 0.5 and suitable variance, and discarding any samples that lie outside of [0,1].
However, you might also be interested in:
- A logitnormal distribution
- A uniform sum distribution
- A raised-cosine distribution
来源:https://stackoverflow.com/questions/8930500/generating-gaussian-distributed-random-numbers-in-c-how-would-one-keep-the-val