C#產生正態分佈、泊松分佈、指數分佈、負指數分佈隨機數(原創)
http://blog.sina.com.cn/s/blog_76c31b8e0100qskf.html
在程式設計過程中,由於資料模擬模擬的需要,我們經常需要產生一些隨機數,在C#中,產生一般隨機數用Random即可,但是,若要產生服從特定分佈的隨機數,就需要一定的演算法來支援了,為了方便廣大程式設計人員,我將我再做專案過程中用到的產生服從正態分佈、泊松分佈、指數分佈以及負指數分佈隨機數的方法與大家共享,希望會有所幫助!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace PZ
{
class Model
{
/// <summary>
/// 正態分佈隨機數
/// </summary>
const int N = 100;
const int MAX = 50;
const double MIN = 0.1;
const int MIU = 40;
const int SIGMA = 1;
static Random aa = new Random((int)(DateTime.Now.Ticks / 10000));
public double AverageRandom(double min, double max)//產生(min,max)之間均勻分佈的隨機數
{
int MINnteger = (int)(min * 10000);
int MAXnteger = (int)(max * 10000);
int resultInteger = aa.Next(MINnteger, MAXnteger);
return resultInteger / 10000.0;
}
public double Normal(double x, double miu, double sigma) //正態分佈概率密度函式
{
return 1.0 / (x * Math.Sqrt(2 * Math.PI) * sigma) * Math.Exp(-1 * (Math.Log(x) - miu) * (Math.Log(x) - miu) / (2 * sigma * sigma));
}
public double Random_Normal(double miu, double sigma, double min, double max)//產生正態分佈隨機數
{
double x;
double dScope;
double y;
do
{
x = AverageRandom(min, max);