Random类是一个产生伪随机数字的类,它的构造函数有两种,一个是直接New Random(),另外一个是New Random(Int32),前者是根据触发那刻的系统时间做为种子,来产生一个随机数字,后者可以自己设定触发的种子,一般都是用UnCheck((Int)DateTime.Now.Ticks)做为参数种子,因此如果计算机运行速度很快,如果触发Randm函数间隔时间很短,就有可能造成产生一样的随机数,因为伪随机的数字,在Random的内部产生机制中还是有一定规律的,并非是真正意义上的完全随机。
Random 快速连续产生不相同随机数的解决方案:
1、延时的办法。
可以采用for循环的办法,也可以采用Thread.Sleep(100);
2、提高随机数不重复概率的种子生成方法:
C#
public double getNum() { Random ro = new Random(GetRandomSeed()); return ro.NextDouble();
}
public int GetRandomSeed() { byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); return BitConverter.ToInt32(bytes, 0); }
VB
Public Function getNum() As Double
Dim ro As Random = New Random(GetRandomSeed()) Return ro.NextDouble()
End Function
Public Function GetRandomSeed() As Integer Dim bytes As Byte() = New Byte(3) {} Dim rng As New System.Security.Cryptography.RNGCryptoServiceProvider() rng.GetBytes(bytes) Return BitConverter.ToInt32(bytes, 0) End Function
VB
Public Function getNum() As Double Randomize() Return Rnd() End Function
|