posts - 134,comments - 22,trackbacks - 0

          使用了 G. E. P. Box、M. E. Muller 和 G. Marsaglia 的極坐標(biāo)法 (polar method)生成符合高斯分布的隨機(jī)數(shù)

           1#include <time.h>
           2#include <stdio.h>
           3#include <stdlib.h>
           4#include <math.h>
           5
           6/*生成符合0-1均勻分布的隨機(jī)數(shù)*/
           7double randf()
           8{
           9    return (double)rand()/RAND_MAX;
          10}

          11
          12
          13/* 高斯分布隨機(jī)數(shù)生成器 */
          14/* 均值 m, 標(biāo)準(zhǔn)差 s */
          15double randomGaussian(double m, double s)    
          16{                        
          17    double x1, x2, w, y1;
          18    static double y2;
          19    static bool haveNext= false;
          20
          21    if (haveNext)                
          22    {
          23        y1 = y2;
          24        haveNext = false;
          25    }

          26    else
          27    {
          28        do 
          29        {
          30            x1 = 2.0 * randf() - 1.0;
          31            x2 = 2.0 * randf() - 1.0;
          32            w = x1 * x1 + x2 * x2;
          33        }

          34        while ( w >= 1.0 || w==0);
          35        
          36        w = sqrt( (-2.0 * log( w ) ) / w );
          37        y1 = x1 * w;
          38        y2 = x2 * w;
          39        haveNext = true;
          40    }

          41    
          42    return( m + y1 * s );
          43}

          44
          45void main()
          46{
          47    srand((unsigned)time( NULL )); //初始化隨機(jī)種子
          48
          49    //生成10個(gè)服從均值為0  標(biāo)準(zhǔn)差為1的高斯分布的隨機(jī)數(shù)
          50    double tmp;
          51
          52    for(int i=0;i<10;i++)
          53    {
          54        tmp=randomGaussian(0,1);
          55        printf("%f\n",tmp);
          56    }

          57}
          結(jié)果圖:

          參考:http://www.taygeta.com/random/gaussian.html
          posted on 2009-02-26 15:22 何克勤 閱讀(1355) 評(píng)論(0)  編輯  收藏

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 桃江县| 延津县| 岳西县| 邵阳县| 绥宁县| 本溪| 星子县| 伊川县| 儋州市| 临潭县| 绥化市| 霍邱县| 临泉县| 和林格尔县| 张家界市| 韶关市| 常宁市| 石家庄市| 富平县| 雅安市| 东乌珠穆沁旗| 军事| 淅川县| 司法| 霍山县| 天峻县| 菏泽市| 贵德县| 盘山县| 罗田县| 射洪县| 霍州市| 孝昌县| 习水县| 棋牌| SHOW| 灯塔市| 新巴尔虎左旗| 自贡市| 高要市| 丰城市|