• 【C#】Random类中构造方法、时间种子与随机数序列的关系


    Random类

    构造函数

    1) Random random = new Random(); // 无参数构造函数使用系统时钟生成其种子值

    然而,系统时钟取值范围有限,因此在小规模计算中,可能无法使用不同的种子值分别调用此构造函数, 这将导致两个random对象生成相同的随机数字序列。

     1 using System;
     2 using System.Collections.Generic;
     3 
     4 namespace FirstTest
     5 {
     6     class Program
     7     {
     8         static void Main(string[] args)
     9         {
    10             Random random1 = new Random();
    11             List<int> list1 = new List<int>();
    12             GetRandomNumbers(random1, list1);
    13             Console.WriteLine("random1对象使用默认构造函数生成的随机数序列: ");
    14             PrintList(list1);
    15 
    16             Random random2 = new Random();
    17             List<int> list2 = new List<int>();
    18             GetRandomNumbers(random2, list2);
    19             Console.WriteLine("random2对象使用默认构造函数生成的随机数序列: ");
    20             PrintList(list2);
    21         }
    22 
    23         private static void GetRandomNumbers(Random rand, List<int> list)
    24         {
    25             for (int i = 1; i <= 15; i++)
    26             {
    27                 list.Add(rand.Next(0, 100));
    28             }
    29         }
    30 
    31         private static void PrintList(List<int> list)
    32         {
    33             foreach (int element in list)
    34             {
    35                 Console.Write ("{0, 5}", element);
    36             }
    37             Console.WriteLine();
    38         }
    39     }
    40 }

    运行结果:

    2) Random random = new Random(Int32); // 参数化构造函数使用指定的种子值初始化Random类实例,如果指定的是负数,则使用其绝对值作为时间种子。

    创建随时间推移,时间种子取值范围大的 Random 对象,以确保生成多个Random对象时,彼此间的随机数序列不同。

    • 通常情况下使用计时周期数(Ticks)作为时间种子:

     1 Random random = new Random((int)DateTime.Now.Ticks); 

     运行结果:

     

    • 或者,通过加密随机数生成器(RNG)生成时间种子:
    1 Random random = new Random(GetRandomSeed());
    2 
    3 static int GetRandomSeed()
    4 {
    5     byte[] bytes = new byte[4];
    6     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
    7     rng.GetBytes(bytes);
    8     return BitConverter.ToInt32(bytes, 0);
    9 }

    运行结果:

  • 相关阅读:
    SQL查询语句精华使用简要
    配置文件中映射元素详解
    从软件工程师到IT猎头:我的一点经历和感触
    配置文件中映射元素详解
    SQL查询语句精华使用简要
    从软件工程师到IT猎头:我的一点经历和感触
    谈谈对软件项目成员的业绩考核
    谈谈对软件项目成员的业绩考核
    五十条经典的做人哲学
    Ubuntu 12.10使用心得
  • 原文地址:https://www.cnblogs.com/muxiaomo/p/4480790.html
Copyright © 2020-2023  润新知