生成高斯分布的随机数用C - 如何将一个保0和1之间的值 [英] Generating Gaussian Distributed Random Numbers in C - how would one keep the values between 0 and 1

查看:338
本文介绍了生成高斯分布的随机数用C - 如何将一个保0和1之间的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直工作在一个函数生成rel=\"nofollow\">这种零和1 是因为我基本上是复制的算法极坐标形式来获取过程的理解有很大的帮助,但我有麻烦保持在0和1之间的值,包括0但不包括1,我相信数学记法,这是[0,1)如果我是正确的。您可以提供任何有识之士将是巨大的。在Unix上,这与编译; GCC的文件名的.C -lm

 的#include<&limits.h中GT;
#包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&time.h中GT;
#包括LT&;&math.h中GT;诠释的main()
{
    INT I;
    浮法X,W;
    对于(i = 0; I< 50;我++)
    {
        做{
            X = 2.0 *((浮点)兰特()/(浮点)RAND_MAX) - 1.0;
            W = X * X;
        }而(并且R w = 1.0);        W =(浮动)的sqrt((-2.0 *日志(W))/ W);
        的printf(%F \\ N,X * W)
    }
    返回0;
}


我相信提问是要求像一个的截断高斯分布的。你可以简单地从高斯分布均值为0.5,适合变化产生的样本,并丢弃的谎言之外的任何样品采样这样的分布[0,1]。

不过,您也可能会感兴趣的:

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;
}

解决方案

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:

这篇关于生成高斯分布的随机数用C - 如何将一个保0和1之间的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆