這種結果的原因在於,Random()函數的預設種子是時間,但在迴圈中產生隨機數時,由於運算速度太快,用做種子的時間是相同的(毫秒級),因此產生的隨機數序列是相同的,這樣最終的隨機數就會相同。(基於“線性同餘法”的隨機數發生器)
解決方案是,產生一個通用唯一識別碼,使用它的雜湊值來做種子產生隨機數。代碼如下:
複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace Calculation
{
public static class RandomStatic
{
//產生[0,1)的隨機小數
public static double ProduceDblRandom()
{
Random r = new Random(Guid.NewGuid().GetHashCode());//使用Guid的雜湊值做種子
return r.NextDouble();
}
//產生制定範圍內的隨機整數
public static int ProduceIntRandom(int minValue, int maxValue)
{
Random r = new Random(Guid.NewGuid().GetHashCode());
return r.Next(minValue, maxValue + 1);
}
}
}
這樣在迴圈中產生隨機數就能基本保證其隨機性了,使用該靜態類的代碼如下: 複製代碼 代碼如下://使用上述靜態類
private void button1_Click_1(object sender, EventArgs e)
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(RandomStatic.ProduceIntRandom(0,100));
}
}
//使用預設時間種子
private void button2_Click_1(object sender, EventArgs e)
{
Random r = new Random();
for (int i = 0; i < 100; i++)
{
Console.WriteLine(r.Next(0,100));
}
}
上述代碼中的第一個迴圈可以產生100個很好的位於0-100的隨機數,而第二個迴圈,由於使用預設的時間種子,在這個迴圈中,產生的隨機數序列明顯具有相關性,可以將兩個迴圈產生的隨機數序列放在excel中,做成散佈圖,結果一目瞭然。本來想上傳圖片的,但csdn好像現在上傳不了圖片。
第一個迴圈的結果:
37
66
70
82
82
58
85
60
78
13
3
9
75
83
63
43
50
11
56
13
79
58
30
7
84
5
92
48
83
3
5
29
36
29
8
82
20
1
46
49
17
87
95
35
62
20
51
97
18
41
26
28
63
90
59
76
23
94
11
63
12
37
2
54
23
24
66
86
23
65
3
86
25
85
22
43
17
53
86
89
51
14
59
46
66
54
2
58
75
2
88
99
87
9
31
96
92
8
89
23
第二個迴圈的結果:
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43
43