Random 类 (System) 您所在的位置:网站首页 在线随机数生成器带小数 Random 类 (System)

Random 类 (System)

2023-11-17 01:29| 来源: 网络整理| 查看: 265

Random 类 参考 定义 命名空间: System 程序集:System.Runtime.Extensions.dll 程序集:System.Runtime.dll 程序集:mscorlib.dll 程序集:netstandard.dll

重要

一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。

表示伪随机数生成器,这是一种能够产生满足某些随机性统计要求的数字序列的算法。

public ref class Random public class Random [System.Serializable] public class Random [System.Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class Random type Random = class [] type Random = class [] [] type Random = class Public Class Random 继承 Object Random 属性 SerializableAttribute ComVisibleAttribute 示例

以下示例创建一个随机数生成器,并调用其 NextBytes、 Next和 NextDouble 方法来生成不同范围内的随机数序列。

using namespace System; void main() { // Instantiate random number generator using system-supplied value as seed. Random^ rand = gcnew Random(); // Generate and display 5 random byte (integer) values. array^ bytes = gcnew array(4); rand->NextBytes(bytes); Console::WriteLine("Five random byte values:"); for each (Byte byteValue in bytes) Console::Write("{0, 5}", byteValue); Console::WriteLine(); // Generate and display 5 random integers. Console::WriteLine("Five random integer values:"); for (int ctr = 0; ctr Next()); Console::WriteLine(); // Generate and display 5 random integers between 0 and 100.// Console::WriteLine("Five random integers between 0 and 100:"); for (int ctr = 0; ctr Next(101)); Console::WriteLine(); // Generate and display 5 random integers from 50 to 100. Console::WriteLine("Five random integers between 50 and 100:"); for (int ctr = 0; ctr Next(50, 101)); Console::WriteLine(); // Generate and display 5 random floating point values from 0 to 1. Console::WriteLine("Five Doubles."); for (int ctr = 0; ctr NextDouble()); Console::WriteLine(); // Generate and display 5 random floating point values from 0 to 5. Console::WriteLine("Five Doubles between 0 and 5."); for (int ctr = 0; ctr NextDouble() * 5); } // The example displays output like the following: // Five random byte values: // 194 185 239 54 116 // Five random integer values: // 507,353,531 1,509,532,693 2,125,074,958 1,409,512,757 652,767,128 // Five random integers between 0 and 100: // 16 78 94 79 52 // Five random integers between 50 and 100: // 56 66 96 60 65 // Five Doubles. // 0.943 0.108 0.744 0.563 0.415 // Five Doubles between 0 and 5. // 2.934 3.130 0.292 1.432 4.369 // Instantiate random number generator using system-supplied value as seed. var rand = new Random(); // Generate and display 5 random byte (integer) values. var bytes = new byte[5]; rand.NextBytes(bytes); Console.WriteLine("Five random byte values:"); foreach (byte byteValue in bytes) Console.Write("{0, 5}", byteValue); Console.WriteLine(); // Generate and display 5 random integers. Console.WriteLine("Five random integer values:"); for (int ctr = 0; ctr ThrowIfCancellationRequested(); Monitor::Enter(randLock); result = rand->NextDouble(); Monitor::Exit(randLock); // Check for corruption of Random instance. if ((result == previous) && result == 0) { source->Cancel(); } else { previous = result; } perThreadCtr++; perThreadTotal += result; } Console::WriteLine("Thread {0} finished execution.", Thread::CurrentThread->Name); Console::WriteLine("Random numbers generated: {0:N0}", perThreadCtr); Console::WriteLine("Sum of random numbers: {0:N2}", perThreadTotal); Console::WriteLine("Random number mean: {0:N4}\n", perThreadTotal/perThreadCtr); // Update overall totals. Monitor::Enter(numericLock); totalCount += perThreadCtr; totalValue += perThreadTotal; Monitor::Exit(numericLock); } catch (OperationCanceledException^ e) { Console::WriteLine("Corruption in Thread {1}", e->GetType()->Name, Thread::CurrentThread->Name); } finally { countdown->Signal(); } } }; void main() { Example^ ex = gcnew Example(); Thread::CurrentThread->Name = "Main"; ex->Execute(); } // The example displays output like the following: // Thread 6 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 1,000,491.05 // Random number mean: 0.5002 // // Thread 10 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,329.64 // Random number mean: 0.4997 // // Thread 4 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 1,000,166.89 // Random number mean: 0.5001 // // Thread 8 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,628.37 // Random number mean: 0.4998 // // Thread Main finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,920.89 // Random number mean: 0.5000 // // Thread 3 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,370.45 // Random number mean: 0.4997 // // Thread 7 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,330.92 // Random number mean: 0.4997 // // Thread 9 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 1,000,172.79 // Random number mean: 0.5001 // // Thread 5 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 1,000,079.43 // Random number mean: 0.5000 // // Thread 1 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,817.91 // Random number mean: 0.4999 // // Thread 2 finished execution. // Random numbers generated: 2,000,000 // Sum of random numbers: 999,930.63 // Random number mean: 0.5000 // // // Total random numbers generated: 22,000,000 // Total sum of all random numbers: 10,998,238.98 // Random number mean: 0.4999 using System; using System.Threading; public class Example { [ThreadStatic] static double previous = 0.0; [ThreadStatic] static int perThreadCtr = 0; [ThreadStatic] static double perThreadTotal = 0.0; static CancellationTokenSource source; static CountdownEvent countdown; static Object randLock, numericLock; static Random rand; double totalValue = 0.0; int totalCount = 0; public Example() { rand = new Random(); randLock = new Object(); numericLock = new Object(); countdown = new CountdownEvent(1); source = new CancellationTokenSource(); } public static void Main() { Example ex = new Example(); Thread.CurrentThread.Name = "Main"; ex.Execute(); } private void Execute() { CancellationToken token = source.Token; for (int threads = 1; threads result result () let ex = Example() Thread.CurrentThread.Name Next(-10, 11)); } } // The example displays output like the following: // 2 9 -3 2 4 -7 -3 -8 -8 5 Random rnd = new Random(); for (int ctr = 0; ctr < 10; ctr++) { Console.Write("{0,3} ", rnd.Next(-10, 11)); } // The example displays output like the following: // 2 9 -3 2 4 -7 -3 -8 -8 5 let rnd = Random() for i = 0 to 9 do printf "%3i " (rnd.Next(-10, 11)) // The example displays output like the following: // 2 9 -3 2 4 -7 -3 -8 -8 5 Module Example Public Sub Main() Dim rnd As New Random() For ctr As Integer = 0 To 9 Console.Write("{0,3} ", rnd.Next(-10, 11)) Next End Sub End Module ' The example displays output like the following: ' 2 9 -3 2 4 -7 -3 -8 -8 5

通过调用 NextDouble 方法,从 0.0 到小于 1.0 的单个浮点值。 方法返回的随机数的独占上限为 1,因此其实际上限为 0.999999999999999978。 以下示例生成 10 个随机浮点数。

using namespace System; void main() { Random^ rnd = gcnew Random(); for (int ctr = 0; ctr < 10; ctr++) { Console::Write("{0,-19:R} ", rnd->NextDouble()); if ((ctr + 1) % 3 == 0) Console::WriteLine(); } } // The example displays output like the following: // 0.7911680553998649 0.0903414949264105 0.79776258291572455 // 0.615568345233597 0.652644504165577 0.84023809378977776 // 0.099662564741290441 0.91341467383942321 0.96018602045261581 // 0.74772306473354022 Random rnd = new Random(); for (int ctr = 0; ctr < 10; ctr++) { Console.Write("{0,-19:R} ", rnd.NextDouble()); if ((ctr + 1) % 3 == 0) Console.WriteLine(); } // The example displays output like the following: // 0.7911680553998649 0.0903414949264105 0.79776258291572455 // 0.615568345233597 0.652644504165577 0.84023809378977776 // 0.099662564741290441 0.91341467383942321 0.96018602045261581 // 0.74772306473354022 let rnd = Random() for i = 0 to 9 do printf $"{rnd.NextDouble(),-19:R} " if (i + 1) % 3 = 0 then printfn "" // The example displays output like the following: // 0.7911680553998649 0.0903414949264105 0.79776258291572455 // 0.615568345233597 0.652644504165577 0.84023809378977776 // 0.099662564741290441 0.91341467383942321 0.96018602045261581 // 0.74772306473354022 Module Example Public Sub Main() Dim rnd As New Random() For ctr As Integer = 0 To 9 Console.Write("{0,-19:R} ", rnd.NextDouble()) If (ctr + 1) Mod 3 = 0 Then Console.WriteLine() Next End Sub End Module ' The example displays output like the following: ' 0.7911680553998649 0.0903414949264105 0.79776258291572455 ' 0.615568345233597 0.652644504165577 0.84023809378977776 ' 0.099662564741290441 0.91341467383942321 0.96018602045261581 ' 0.74772306473354022

重要

方法 Next(Int32, Int32) 允许指定返回的随机数的范围。 但是, maxValue 参数(指定返回的上限范围)是一个独占值,而不是非独占值。 这意味着方法调用 Next(0, 100) 返回一个介于 0 和 99 之间的值,而不是 0 到 100 之间的值。

还可以将 Random 类用于以下任务 :生成随机 T:System.Boolean 值、生成 范围不是 0 到 1 的随机浮点值、生成 随机 64 位整数,以及 从数组或集合中随机检索唯一元素。 有关这些任务和其他常见任务,请参阅 如何使用 System.Random to... 部分。

替换你自己的算法

可以通过从 Random 类继承并提供随机数生成算法来实现自己的随机数生成器。 若要提供自己的算法,必须重写 Sample 实现随机数生成算法的 方法。 还应重写 Next()、 Next(Int32, Int32)和 NextBytes 方法,以确保它们调用重写 Sample 的方法。 无需重写 Next(Int32) 和 NextDouble 方法。

有关派生自 Random 类并修改其默认伪随机数生成器的示例,请参阅 Sample 参考页。

如何使用 System.Random...

以下部分讨论并提供了一些你可能想要在应用中使用随机数的方式的示例代码。

检索相同的随机值序列

有时,你想要在软件测试方案和游戏中生成相同的随机数序列。 使用相同的随机数序列进行测试,可以检测回归并确认 bug 修复。 在游戏中使用相同的随机数序列可以重播以前的游戏。

可以通过向构造函数提供相同的种子值来 Random(Int32) 生成相同的随机数序列。 种子值为伪随机数生成算法提供起始值。 以下示例使用 100100 作为任意种子值来实例化 Random 对象,显示 20 个随机浮点值,并保留种子值。 然后,它还原种子值,实例化新的随机数生成器,并显示相同的 20 个随机浮点值。 请注意,如果在不同版本的 .NET Framework上运行,该示例可能会生成不同的随机数序列。

using System; using System.IO; public class Example { public static void Main() { int seed = 100100; ShowRandomNumbers(seed); Console.WriteLine(); PersistSeed(seed); DisplayNewRandomNumbers(); } private static void ShowRandomNumbers(int seed) { Random rnd = new Random(seed); for (int ctr = 0; ctr Close(); } static void DisplayNewRandomNumbers() { FileStream^ fs = gcnew FileStream(".\\seed.dat", FileMode::Open); BinaryReader^ bin = gcnew BinaryReader(fs); int seed = bin->ReadInt32(); bin->Close(); Random^ rnd = gcnew Random(seed); for (int ctr = 0; ctr NextDouble()); } }; void main() { int seed = 100100; RandomMethods::ShowRandomNumbers(seed); Console::WriteLine(); RandomMethods::PersistSeed(seed); RandomMethods::DisplayNewRandomNumbers(); } // The example displays output like the following: // 0.500193602172748 // 0.0209461245783354 // 0.465869495396442 // 0.195512794514891 // 0.928583675496552 // 0.729333720509584 // 0.381455668891527 // 0.0508996467343064 // 0.019261200921266 // 0.258578445417145 // 0.0177532266908107 // 0.983277184415272 // 0.483650274334313 // 0.0219647376900375 // 0.165910115077118 // 0.572085966622497 // 0.805291457942357 // 0.927985211335116 // 0.4228545699375 // 0.523320379910674 // 0.157783938645285 // // 0.500193602172748 // 0.0209461245783354 // 0.465869495396442 // 0.195512794514891 // 0.928583675496552 // 0.729333720509584 // 0.381455668891527 // 0.0508996467343064 // 0.019261200921266 // 0.258578445417145 // 0.0177532266908107 // 0.983277184415272 // 0.483650274334313 // 0.0219647376900375 // 0.165910115077118 // 0.572085966622497 // 0.805291457942357 // 0.927985211335116 // 0.4228545699375 // 0.523320379910674 // 0.157783938645285 Imports System.IO Module Example Public Sub Main() Dim seed As Integer = 100100 ShowRandomNumbers(seed) Console.WriteLine() PersistSeed(seed) DisplayNewRandomNumbers() End Sub Private Sub ShowRandomNumbers(seed As Integer) Dim rnd As New Random(seed) For ctr As Integer = 0 To 20 Console.WriteLine(rnd.NextDouble()) Next End Sub Private Sub PersistSeed(seed As Integer) Dim fs As New FileStream(".\seed.dat", FileMode.Create) Dim bin As New BinaryWriter(fs) bin.Write(seed) bin.Close() End Sub Private Sub DisplayNewRandomNumbers() Dim fs As New FileStream(".\seed.dat", FileMode.Open) Dim bin As New BinaryReader(fs) Dim seed As Integer = bin.ReadInt32() bin.Close() Dim rnd As New Random(seed) For ctr As Integer = 0 To 20 Console.WriteLine(rnd.NextDouble()) Next End Sub End Module ' The example displays output like the following: ' 0.500193602172748 ' 0.0209461245783354 ' 0.465869495396442 ' 0.195512794514891 ' 0.928583675496552 ' 0.729333720509584 ' 0.381455668891527 ' 0.0508996467343064 ' 0.019261200921266 ' 0.258578445417145 ' 0.0177532266908107 ' 0.983277184415272 ' 0.483650274334313 ' 0.0219647376900375 ' 0.165910115077118 ' 0.572085966622497 ' 0.805291457942357 ' 0.927985211335116 ' 0.4228545699375 ' 0.523320379910674 ' 0.157783938645285 ' ' 0.500193602172748 ' 0.0209461245783354 ' 0.465869495396442 ' 0.195512794514891 ' 0.928583675496552 ' 0.729333720509584 ' 0.381455668891527 ' 0.0508996467343064 ' 0.019261200921266 ' 0.258578445417145 ' 0.0177532266908107 ' 0.983277184415272 ' 0.483650274334313 ' 0.0219647376900375 ' 0.165910115077118 ' 0.572085966622497 ' 0.805291457942357 ' 0.927985211335116 ' 0.4228545699375 ' 0.523320379910674 ' 0.157783938645285

检索随机数的唯一序列

向 类的 Random 实例提供不同的种子值会导致每个随机数生成器生成不同的值序列。 可以通过调用 Random(Int32) 构造函数显式提供种子值,也可以通过调用 Random() 构造函数隐式提供种子值。 大多数开发人员调用使用系统时钟的无参数构造函数。 以下示例使用此方法实例化两 Random 个实例。 每个实例显示一系列 10 个随机整数。

using namespace System; using namespace System::Threading; void main() { Console::WriteLine("Instantiating two random number generators..."); Random^ rnd1 = gcnew Random(); Thread::Sleep(2000); Random^ rnd2 = gcnew Random(); Console::WriteLine("\nThe first random number generator:"); for (int ctr = 1; ctr Next()); Console::WriteLine("\nThe second random number generator:"); for (int ctr = 1; ctr Next()); } // The example displays output like the following: // Instantiating two random number generators... // // The first random number generator: // 643164361 // 1606571630 // 1725607587 // 2138048432 // 496874898 // 1969147632 // 2034533749 // 1840964542 // 412380298 // 47518930 // // The second random number generator: // 1251659083 // 1514185439 // 1465798544 // 517841554 // 1821920222 // 195154223 // 1538948391 // 1548375095 // 546062716 // 897797880 using System; using System.Threading; public class Example { public static void Main() { Console.WriteLine("Instantiating two random number generators..."); Random rnd1 = new Random(); Thread.Sleep(2000); Random rnd2 = new Random(); Console.WriteLine("\nThe first random number generator:"); for (int ctr = 1; ctr Next(0, 2)); } }; void main() { // Instantiate the Boolean generator. BooleanGenerator^ boolGen = gcnew BooleanGenerator(); int totalTrue = 0, totalFalse = 0; // Generate 1,0000 random Booleans, and keep a running total. for (int ctr = 0; ctr < 1000000; ctr++) { bool value = boolGen->NextBoolean(); if (value) totalTrue++; else totalFalse++; } Console::WriteLine("Number of true values: {0,7:N0} ({1:P3})", totalTrue, ((double) totalTrue)/(totalTrue + totalFalse)); Console::WriteLine("Number of false values: {0,7:N0} ({1:P3})", totalFalse, ((double) totalFalse)/(totalTrue + totalFalse)); } // The example displays output like the following: // Number of true values: 500,004 (50.000 %) // Number of false values: 499,996 (50.000 %) using System; public class Example { public static void Main() { // Instantiate the Boolean generator. BooleanGenerator boolGen = new BooleanGenerator(); int totalTrue = 0, totalFalse = 0; // Generate 1,0000 random Booleans, and keep a running total. for (int ctr = 0; ctr < 1000000; ctr++) { bool value = boolGen.NextBoolean(); if (value) totalTrue++; else totalFalse++; } Console.WriteLine("Number of true values: {0,7:N0} ({1:P3})", totalTrue, ((double) totalTrue)/(totalTrue + totalFalse)); Console.WriteLine("Number of false values: {0,7:N0} ({1:P3})", totalFalse, ((double) totalFalse)/(totalTrue + totalFalse)); } } public class BooleanGenerator { Random rnd; public BooleanGenerator() { rnd = new Random(); } public bool NextBoolean() { return rnd.Next(0, 2) == 1; } } // The example displays output like the following: // Number of true values: 500,004 (50.000 %) // Number of false values: 499,996 (50.000 %) open System type BooleanGenerator() = let rnd = Random() member _.NextBoolean() = rnd.Next(0, 2) = 1 let boolGen = BooleanGenerator() let mutable totalTrue, totalFalse = 0, 0 for _ = 1 to 1000000 do let value = boolGen.NextBoolean() if value then totalTrue


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有