循环中产生伪随机数

来源:互联网 发布:供给侧改革数据分析 编辑:程序博客网 时间:2024/05/19 05:37

 

    在循环中产生多个随机数,容易出现连续相同的数据,最终的多个随机数并不随机,而是带有某种规律性。这种结果的原因在于,Random()函数的默认种子是时间,但在循环中产生随机数时,由于运算速度太快,用做种子的时间是相同的(毫 秒级),因此产生的随机数序列是相同的,这样最终的随机数就会相同。(基于“线性同余法”的随机数发生器)

    解决方法是,产生一个全局唯一标识符,使用它的哈希值来做种子产生随机数。代码如下:

 

[c-sharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Security.Cryptography;  
  6. namespace Calculation  
  7. {  
  8.     public static class RandomStatic  
  9.     {  
  10.         //产生[0,1)的随机小数  
  11.         public static double ProduceDblRandom()  
  12.         {  
  13.             Random r = new Random(Guid.NewGuid().GetHashCode());//使用Guid的哈希值做种子  
  14.             return r.NextDouble();  
  15.         }  
  16.         //产生制定范围内的随机整数  
  17.         public static int ProduceIntRandom(int minValue, int maxValue)  
  18.         {  
  19.             Random r = new Random(Guid.NewGuid().GetHashCode());  
  20.             return r.Next(minValue, maxValue + 1);  
  21.         }  
  22.     }  
  23. }  
 

 

这样在循环中产生随机数就能基本保证其随机性了,使用该静态类的代码如下:

 

[c-sharp] view plaincopy
  1. //使用上述静态类  
  2. private void button1_Click_1(object sender, EventArgs e)  
  3.         {  
  4.             for (int i = 0; i < 100; i++)  
  5.             {  
  6.                 Console.WriteLine(RandomStatic.ProduceIntRandom(0,100));  
  7.             }  
  8.         }  
  9. //使用默认时间种子  
  10. private void button2_Click_1(object sender, EventArgs e)  
  11.         {  
  12.             Random r = new Random();  
  13.             for (int i = 0; i < 100; i++)  
  14.             {  
  15.                 Console.WriteLine(r.Next(0,100));  
  16.             }  
  17.         }  

 

 

上述代码中的第一个循环可以产生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

原创粉丝点击