循环中产生伪随机数

 在循环中产生多个随机数,容易出现连续相同的数据,最终的多个随机数并不随机,而是带有某种规律性。这种结果的原因在于,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)); } } //使用上述静态类 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


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/suinon/archive/2010/03/18/5394356.aspx

你可能感兴趣的:(object,Excel,Random,System,Class,button)