posts - 134,comments - 22,trackbacks - 0

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

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

          11
          12
          13/* 高斯分布隨機數生成器 */
          14/* 均值 m, 標準差 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 )); //初始化隨機種子
          48
          49    //生成10個服從均值為0  標準差為1的高斯分布的隨機數
          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}
          結果圖:

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

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 澳门| 铁力市| 泰顺县| 台州市| 遵义市| 黄冈市| 蕉岭县| 鞍山市| 锦州市| 浮山县| 大同市| 杨浦区| 河津市| 定远县| 乌拉特前旗| 常德市| 衡阳市| 都兰县| 岗巴县| 儋州市| 宝丰县| 大丰市| 黔西| 芜湖县| 互助| 岳西县| 上林县| 河西区| 东明县| 乃东县| 晋州市| 凤台县| 南召县| 南投市| 阿勒泰市| 五原县| 镶黄旗| 鸡西市| 东乌珠穆沁旗| 兰州市| 阳原县|