c#DIY随机数类

王朝学院·作者佚名  2009-02-05
窄屏简体版  字體: |||超大  

在类库横行的今天,请支持DIY ,直接看代码(有注释)

view plaincopy to clipboardprint?

using System;

namespace MyRandom

{

public class Rand

{

private long seed; //随机数种子

//用系统时间作为随机种子

public Rand()

{

string str = DateTime.Now.Day.ToString();

str += DateTime.Now.Hour.ToString();

str += DateTime.Now.Minute.ToString();

str += DateTime.Now.Second.ToString();

str += DateTime.Now.Millisecond.ToString();

this.seed = long.Parse(str);

}

//用户自定义随机种子

public Rand(long Value)

{

this.seed = Value;

}

//产生非负伪随机数

public long Next()

{

long l = this.seed;

l = l * l;

string strTime = l.ToString();

int w = strTime.Length / 3;

string str = "";

for (int i = w; i < strTime.Length - w; i++)

str += strTime[i];

l = long.Parse(str);

return l;

}

//产生上限为Value的伪随机数

public long Next(long Value)

{

if (Value < 0)

return -1;

long l = this.seed;

l = l * l;

string strTime = l.ToString();

int w = strTime.Length / 3;

string str = "";

for (int i = w; i < strTime.Length - w; i++)

str += strTime[i];

l = long.Parse(str);

return l % Value;

}

//产生下限为minValue上限为maxValue的伪随机数

public long Next(long minValue, long maxValue)

{

if (minValue < 0 || maxValue < 0 || minValue > maxValue)

return -1;

long l = this.seed;

l = l * l;

string strTime = l.ToString();

int w = strTime.Length / 3;

string str = "";

for (int i = w; i < strTime.Length - w; i++)

str += strTime[i];

l = long.Parse(str);

return l % (maxValue - minValue) + minValue;

}

//伪随机数填充指定的比特数组

public void NextBytes(byte[] buffer)

{

long Value = 0;

Value = this.Next() % 255;

for (int i = 0; i < buffer.Length; i++)

{

Value = Value * Value;

string strTime = Value.ToString();

int w = strTime.Length / 3;

string str = "";

for (int j = w; j < strTime.Length - w; j++)

str += strTime[j];

Value = long.Parse(str);

Value = Value % 255;

buffer[i] = (byte)Value;

}

}

//产生0.0到1.0的伪随机数

public double NextDouble()

{

long l = this.Next(0, 100000);

if (l == 100000)

return 1.0;

l = l * l;

string strTime = l.ToString();

int w = strTime.Length / 3;

string str = "0.";

for (int i = w; i < strTime.Length - w; i++)

str += strTime[i];

double d = double.Parse(str);

return d;

}

}

}

http://blog.csdn.net/gisfarmer/archive/2009/02/03/3860282.aspx

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航