Generating Gaussian Distributed Random Numbers in C - how would one keep the values between 0 and 1

半世苍凉 提交于 2019-12-11 11:09:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!