c#迴圈中產生偽隨機數

來源:互聯網
上載者:User

這種結果的原因在於,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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.