using?System.Collections.Generic;
using?System.Text;
using?System.IO;
using?System.Collections;
using?System.Text.RegularExpressions;
namespace?random
{
class?Program
{
//求隨機數平均值方法
static?double?Ave(double[]?a)
{?
double?sum=0;
foreach(double?d?in?a)
{
sum=sum+d;
}
double?ave=sum/a.Length;
return?ave;
}
//求隨機數方差方法
static?double?Var(double[]?v)
{
//double?tt?=?2;
//double?mm?=?tt?^?2;
double?sum1?=?0;
for?(int?i?=?0;?i?<?v.Length;?i++)
{
double?temp?=?v[i]?*?v[i];
sum1?=?sum1?+?temp;
}
double?sum?=?0;
foreach?(double?d?in?v)
{
sum?=?sum?+?d;
}
double?var?=?sum1?/?v.Length?-?(sum?/?v.Length)?*?(sum?/?v.Length);
return?var;
}
//求正態分布的隨機數
static?void?Fenbu(double[]?f)
{
//double?fenbu=new?double[f.Length?];
for?(int?i?=?0;?i?<?f.Length;?i++)
{
double?a?=?0,?b?=?0;
a?=Math.Sqrt((-2)*?Math.Log(f[i],?Math.E));
b?=?Math.Cos(2?*?Math.PI?*?f[i]);
f[i]?=?a?*?b?*?0.3?+?1;
}
}
static?void?Main(string[]?args)
{
//生成100個(0,1)之間的隨機數
Random?ran?=?new?Random();
double[]?dou?=?new?double[100];
for(int?i=0;i<dou.Length;i++)
{
dou[i]=?ran.NextDouble();
}
//調用Ave方法、Var方法求得隨機數均值和方差
double?avenum?=?Ave(dou);
double?varnum?=?Var(dou);
//寫入文件
//將100個隨機數,均值,方差保存到文件“d:\C#練習\SourceData.txt”中
string?Datapath?=?(@".\SourceData.txt");
FileStream?fs?=?new?FileStream(Datapath,?FileMode.CreateNew); StreamWriter?sw?=?new?StreamWriter(fs); for?(int?j?=?0;?j?<?dou.Length;j++?) { sw.WriteLine(dou[j]); } sw.Write("100個隨機數均值和方差分別是{0}和{1}",avenum,varnum); sw.Close(); //讀取數據文件“d:\C#練習\SourceData.txt” FileStream?fs1?=?new?FileStream(Datapath,?FileMode.Open); StreamReader?sr?=?new?StreamReader(fs1); string?temp=null; string?str?=?null; while((temp=sr.ReadLine())!=null){
str?=?str+temp+"?";
}
//對數組進行分割Regax
Regex?re?=?new?Regex("?"); string[]?str1=re.Split(str); double[]?nums=new?double[str1.Length-2]; for(int?i=0;i<str1.Length-2;i++) { nums[i]=Convert.ToDouble(str1[i]); }//調用正態分布隨機函數,求均值和方差
Fenbu(nums);
double?averesult=?Ave(nums);
double?varresult?=?Var(nums);
//寫入文件
//將100個隨機數,均值,方差保存到文件“d:\C#練習\ResultData.txt”中
string?Resultpath?=?(@".\ResultData.txt");
FileStream?fs2?=?new?FileStream(Resultpath,?FileMode.Create);
StreamWriter?sw1?=?new?StreamWriter(fs2);
for?(int?j?=?0;?j?<?nums.Length;?j++)
{
sw1.WriteLine(nums[j]);
}
sw1.Write("100個隨機數均值和方差分別是{0}和{1}",?averesult,?varresult);
sw1.Close();
Console.ReadKey();
}
}
}