@zhouweicsu
2017-05-29T22:09:04.000000Z
字数 2104
阅读 708
未分类
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace BoxmullerTest
{
class Program
{
static void Main(string[] args)
{
try{
FileStream fs = new FileStream("E://data.txt",FileMode.Create);
//获得字节数组
double E =20000 ;//正态分布期望
double D =6000;//正态分布方差
double[] ZTFBArr = new double[1000];
int[] ZTFBArrint = new int[1000];
int[] YSArr = new int[1000];
Random u1 = new Random(); Random u2 = new Random();
for (int i = 0; i < 1000; i++)
{
double? result = GetZTFB(u1.NextDouble(), u2.NextDouble(), E, D);
if (result != null){
ZTFBArr[i] = (double)result;
ZTFBArrint[i] = (int)result;
YSArr[i] = 98593110 % ZTFBArrint[i];
byte [] data =new UTF8Encoding().GetBytes(String);
//开始写入
fs.Write(data,0,data.Length);
}
}
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}
catch (IOException e);
{
Console.WriteLine("An IO exception has been thrown!");
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
Console.WriteLine(ZTFBArr.Length);
Console.ReadKey();
for (int i = 0; i < ZTFBArr.Length; i++)
{
Console.Write(string.Format("{0} ",YSArr[i]));
}
Console.ReadKey();
double teste = GetE(ZTFBArr);
double testd = GetD(ZTFBArr, teste);
Console.WriteLine(string.Format("计算期望:{0} 生成期望:{1}", E, teste));
Console.WriteLine(string.Format("计算方差:{0} 生成方差:{1}", D, testd));
Console.ReadKey();
}
/// <summary>
/// 计算数组期望值
/// </summary>
/// <param name="arr"></param>
/// <returns></returns>
private static double GetE(double[] arr)
{
double teste;//测试方差
double sumresult = 0;
for (int i = 0; i < arr.Length; i++)
{
sumresult += arr[i];
}
teste = sumresult / arr.Length;
return teste;
}
/// <summary>
/// 计算数组的方差
/// </summary>
/// <param name="arr"></param>
/// <param name="teste">期望值</param>
/// <returns></returns>
private static double GetD(double[] arr, double teste)
{
double sumd = 0;
for (int i = 0; i < arr.Length; i++)
{
sumd += Math.Pow(arr[i] - teste, 2);
}
return sumd / arr.Length;
}
/// <summary>
/// 返回正态分布的值
/// </summary>
/// <param name="u1">第一个均匀分布值</param>
/// <param name="u2">第二个均匀分布值</param>
/// <param name="e">正态期望</param>
/// <param name="d">正态方差</param>
/// <returns>分布值或者null</returns>
private static double? GetZTFB(double u1, double u2, double e, double d)
{
double? result = null;
try
{
result = e + Math.Sqrt(d) * Math.Sqrt((-2) * (Math.Log(u1) / Math.Log(Math.E))) * Math.Sin(2 * Math.PI * u2);
}
catch (Exception ex)
{
result = null;
}
return result;
}
}
}