Random.Sample 메서드

정의

0.0과 1.0 사이의 임의의 부동 소수점 숫자를 반환합니다.Returns a random floating-point number between 0.0 and 1.0.

protected:
 virtual double Sample();
protected virtual double Sample ();
abstract member Sample : unit -> double
override this.Sample : unit -> double
Protected Overridable Function Sample () As Double

반환

Double

0.0보다 크거나 같고 1.0보다 작은 배정밀도 부동 소수점 숫자입니다.A double-precision floating point number that is greater than or equal to 0.0, and less than 1.0.

예제

다음 예제에서는에서 클래스를 파생 Random 시키고 메서드를 재정의 Sample 하 여 난수 분포를 생성 합니다.The following example derives a class from Random and overrides the Sample method to generate a distribution of random numbers. 이 분포는 Sample 기본 클래스의 메서드에서 생성 된 균일 분포와는 다릅니다.This distribution is different than the uniform distribution generated by the Sample method of the base class.

using namespace System;

// This derived class converts the uniformly distributed random 
// numbers generated by base.Sample() to another distribution.
public ref class RandomProportional : Random
{
    // The Sample method generates a distribution proportional to the value 
    // of the random numbers, in the range [0.0, 1.0].
protected:
   virtual double Sample() override
   {
       return Math::Sqrt(Random::Sample());
   }

public:
   RandomProportional()
   {}
   
   virtual int Next() override
   {
      return (int) (Sample() * Int32::MaxValue);
   }   
};

int main(array<System::String ^> ^args)
{
      const int rows = 4, cols = 6;
      const int runCount = 1000000;
      const int distGroupCount = 10;
      const double intGroupSize = 
         ((double) Int32::MaxValue + 1.0) / (double)distGroupCount;

      RandomProportional ^randObj = gcnew RandomProportional();

      array<int>^ intCounts = gcnew array<int>(distGroupCount);
      array<int>^ realCounts = gcnew array<int>(distGroupCount);

      Console::WriteLine(
         "\nThe derived RandomProportional class overrides " +
         "the Sample method to \ngenerate random numbers " +
         "in the range [0.0, 1.0]. The distribution \nof " +
         "the numbers is proportional to their numeric values. " +
         "For example, \nnumbers are generated in the " +
         "vicinity of 0.75 with three times the \n" +
         "probability of those generated near 0.25.");
      Console::WriteLine(
         "\nRandom doubles generated with the NextDouble() " +
         "method:\n");

      // Generate and display [rows * cols] random doubles.
      for (int i = 0; i < rows; i++)
      {
         for (int j = 0; j < cols; j++) 
               Console::Write("{0,12:F8}", randObj->NextDouble());
         Console::WriteLine();
      }

      Console::WriteLine(
         "\nRandom integers generated with the Next() " +
         "method:\n");

      // Generate and display [rows * cols] random integers.
      for (int i = 0; i < rows; i++)
      {
         for (int j = 0; j < cols; j++)
               Console::Write("{0,12}", randObj->Next());
         Console::WriteLine();
      }

      Console::WriteLine(
         "\nTo demonstrate the proportional distribution, " +
         "{0:N0} random \nintegers and doubles are grouped " +
         "into {1} equal value ranges. This \n" +
         "is the count of values in each range:\n",
         runCount, distGroupCount);
      Console::WriteLine(
         "{0,21}{1,10}{2,20}{3,10}", "Integer Range",
         "Count", "Double Range", "Count");
      Console::WriteLine(
         "{0,21}{1,10}{2,20}{3,10}", "-------------",
         "-----", "------------", "-----");

      // Generate random integers and doubles, and then count 
      // them by group.
      for (int i = 0; i < runCount; i++)
      {
         intCounts[ (int)((double)randObj->Next() / 
               intGroupSize) ]++;
         realCounts[ (int)(randObj->NextDouble() * 
               (double)distGroupCount) ]++;
      }

      // Display the count of each group.
      for (int i = 0; i < distGroupCount; i++)
         Console::WriteLine(
               "{0,10}-{1,10}{2,10:N0}{3,12:N5}-{4,7:N5}{5,10:N0}",
               (int)((double)i * intGroupSize),
               (int)((double)(i + 1) * intGroupSize - 1.0),
               intCounts[ i ],
               ((double)i) / (double)distGroupCount,
               ((double)(i + 1)) / (double)distGroupCount,
               realCounts[ i ]);
      return 0;
}

/*
This example of Random.Sample() displays output similar to the following:

   The derived RandomProportional class overrides the Sample method to
   generate random numbers in the range [0.0, 1.0). The distribution
   of the numbers is proportional to the number values. For example,
   numbers are generated in the vicinity of 0.75 with three times the
   probability of those generated near 0.25.

   Random doubles generated with the NextDouble() method:

     0.59455719  0.17589882  0.83134398  0.35795862  0.91467727  0.54022658
     0.93716947  0.54817519  0.94685080  0.93705478  0.18582318  0.71272428
     0.77708682  0.95386216  0.70412393  0.86099417  0.08275804  0.79108316
     0.71019941  0.84205103  0.41685082  0.58186880  0.89492302  0.73067715

   Random integers generated with the Next() method:

     1570755704  1279192549  1747627711  1705700211  1372759203  1849655615
     2046235980  1210843924  1554274149  1307936697  1480207570  1057595022
      337854215   844109928  2028310798  1386669369  2073517658  1291729809
     1537248240  1454198019  1934863511  1640004334  2032620207   534654791

   To demonstrate the proportional distribution, 1,000,000 random
   integers and doubles are grouped into 10 equal value ranges. This
   is the count of values in each range:

           Integer Range     Count        Double Range     Count
           -------------     -----        ------------     -----
            0- 214748363    10,079     0.00000-0.10000    10,148
    214748364- 429496728    29,835     0.10000-0.20000    29,849
    429496729- 644245093    49,753     0.20000-0.30000    49,948
    644245094- 858993458    70,325     0.30000-0.40000    69,656
    858993459-1073741823    89,906     0.40000-0.50000    90,337
   1073741824-1288490187   109,868     0.50000-0.60000   110,225
   1288490188-1503238552   130,388     0.60000-0.70000   129,986
   1503238553-1717986917   149,231     0.70000-0.80000   150,428
   1717986918-1932735282   170,234     0.80000-0.90000   169,610
   1932735283-2147483647   190,381     0.90000-1.00000   189,813
*/
using System;

// This derived class converts the uniformly distributed random
// numbers generated by base.Sample() to another distribution.
public class RandomProportional : Random
{
    // The Sample method generates a distribution proportional to the value
    // of the random numbers, in the range [0.0, 1.0].
    protected override double Sample()
    {
        return Math.Sqrt(base.Sample());
    }

    public override int Next()
    {
       return (int) (Sample() * int.MaxValue);
    }
}

public class RandomSampleDemo
{
    static void Main()
    {	
        const int rows = 4, cols = 6;
        const int runCount = 1000000;
        const int distGroupCount = 10;
        const double intGroupSize =
            ((double)int.MaxValue + 1.0) / (double)distGroupCount;

        RandomProportional randObj = new RandomProportional();

        int[ ]      intCounts = new int[ distGroupCount ];
        int[ ]      realCounts = new int[ distGroupCount ];

        Console.WriteLine(
            "\nThe derived RandomProportional class overrides " +
            "the Sample method to \ngenerate random numbers " +
            "in the range [0.0, 1.0]. The distribution \nof " +
            "the numbers is proportional to their numeric values. " +
            "For example, \nnumbers are generated in the " +
            "vicinity of 0.75 with three times the \n" +
            "probability of those generated near 0.25.");
        Console.WriteLine(
            "\nRandom doubles generated with the NextDouble() " +
            "method:\n");

        // Generate and display [rows * cols] random doubles.
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
                Console.Write("{0,12:F8}", randObj.NextDouble());
            Console.WriteLine();
        }

        Console.WriteLine(
            "\nRandom integers generated with the Next() " +
            "method:\n");

        // Generate and display [rows * cols] random integers.
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
                Console.Write("{0,12}", randObj.Next());
            Console.WriteLine();
        }

        Console.WriteLine(
            "\nTo demonstrate the proportional distribution, " +
            "{0:N0} random \nintegers and doubles are grouped " +
            "into {1} equal value ranges. This \n" +
            "is the count of values in each range:\n",
            runCount, distGroupCount);
        Console.WriteLine(
            "{0,21}{1,10}{2,20}{3,10}", "Integer Range",
            "Count", "Double Range", "Count");
        Console.WriteLine(
            "{0,21}{1,10}{2,20}{3,10}", "-------------",
            "-----", "------------", "-----");

        // Generate random integers and doubles, and then count
        // them by group.
        for (int i = 0; i < runCount; i++)
        {
            intCounts[ (int)((double)randObj.Next() /
                intGroupSize) ]++;
            realCounts[ (int)(randObj.NextDouble() *
                (double)distGroupCount) ]++;
        }

        // Display the count of each group.
        for (int i = 0; i < distGroupCount; i++)
            Console.WriteLine(
                "{0,10}-{1,10}{2,10:N0}{3,12:N5}-{4,7:N5}{5,10:N0}",
                (int)((double)i * intGroupSize),
                (int)((double)(i + 1) * intGroupSize - 1.0),
                intCounts[ i ],
                ((double)i) / (double)distGroupCount,
                ((double)(i + 1)) / (double)distGroupCount,
                realCounts[ i ]);
    }
}

/*
This example of Random.Sample() displays output similar to the following:

   The derived RandomProportional class overrides the Sample method to
   generate random numbers in the range [0.0, 1.0). The distribution
   of the numbers is proportional to the number values. For example,
   numbers are generated in the vicinity of 0.75 with three times the
   probability of those generated near 0.25.

   Random doubles generated with the NextDouble() method:

     0.59455719  0.17589882  0.83134398  0.35795862  0.91467727  0.54022658
     0.93716947  0.54817519  0.94685080  0.93705478  0.18582318  0.71272428
     0.77708682  0.95386216  0.70412393  0.86099417  0.08275804  0.79108316
     0.71019941  0.84205103  0.41685082  0.58186880  0.89492302  0.73067715

   Random integers generated with the Next() method:

     1570755704  1279192549  1747627711  1705700211  1372759203  1849655615
     2046235980  1210843924  1554274149  1307936697  1480207570  1057595022
      337854215   844109928  2028310798  1386669369  2073517658  1291729809
     1537248240  1454198019  1934863511  1640004334  2032620207   534654791

   To demonstrate the proportional distribution, 1,000,000 random
   integers and doubles are grouped into 10 equal value ranges. This
   is the count of values in each range:

           Integer Range     Count        Double Range     Count
           -------------     -----        ------------     -----
            0- 214748363    10,079     0.00000-0.10000    10,148
    214748364- 429496728    29,835     0.10000-0.20000    29,849
    429496729- 644245093    49,753     0.20000-0.30000    49,948
    644245094- 858993458    70,325     0.30000-0.40000    69,656
    858993459-1073741823    89,906     0.40000-0.50000    90,337
   1073741824-1288490187   109,868     0.50000-0.60000   110,225
   1288490188-1503238552   130,388     0.60000-0.70000   129,986
   1503238553-1717986917   149,231     0.70000-0.80000   150,428
   1717986918-1932735282   170,234     0.80000-0.90000   169,610
   1932735283-2147483647   190,381     0.90000-1.00000   189,813
*/
' This derived class converts the uniformly distributed random 
' numbers generated by base.Sample() to another distribution.
Public Class RandomProportional
   Inherits Random

   ' The Sample method generates a distribution proportional to the value 
   ' of the random numbers, in the range [0.0, 1.0].
   Protected Overrides Function Sample() As Double
      Return Math.Sqrt(MyBase.Sample())
   End Function
   
   Public Overrides Function [Next]() As Integer
      Return Sample() * Integer.MaxValue
   End Function 
End Class 

Module RandomSampleDemo
    Sub Main()
        Const rows As Integer = 4, cols As Integer = 6
        Const runCount As Integer = 1000000
        Const distGroupCount As Integer = 10
        Const intGroupSize As Double = _
            (CDbl(Integer.MaxValue) + 1.0) / _
            CDbl(distGroupCount)
            
        Dim randObj As New RandomProportional()
            
        Dim intCounts(distGroupCount) As Integer
        Dim realCounts(distGroupCount) As Integer
        Dim i As Integer, j As Integer 
            
        Console.WriteLine(vbCrLf & _
            "The derived RandomProportional class overrides " & _ 
            "the Sample method to " & vbCrLf & _
            "generate random numbers in the range " & _ 
            "[0.0, 1.0]. The distribution " & vbCrLf & _
            "of the numbers is proportional to their numeric " & _
            "values. For example, " & vbCrLf & _ 
            "numbers are generated in the vicinity of 0.75 " & _
            "with three times " & vbCrLf & "the " & _
            "probability of those generated near 0.25.")
        Console.WriteLine(vbCrLf & _
            "Random doubles generated with the NextDouble() " & _ 
            "method:" & vbCrLf)
            
        ' Generate and display [rows * cols] random doubles.
        For i = 0 To rows - 1
            For j = 0 To cols - 1
                Console.Write("{0,12:F8}", randObj.NextDouble())
            Next j
            Console.WriteLine()
        Next i
            
        Console.WriteLine(vbCrLf & _
            "Random integers generated with the Next() " & _ 
            "method:" & vbCrLf)
            
        ' Generate and display [rows * cols] random integers.
        For i = 0 To rows - 1
            For j = 0 To cols - 1
                Console.Write("{0,12}", randObj.Next())
            Next j
            Console.WriteLine()
        Next i
            
        Console.WriteLine(vbCrLf & _
            "To demonstrate the proportional distribution, " & _ 
            "{0:N0} random " & vbCrLf & _
            "integers and doubles are grouped into {1} " & _ 
            "equal value ranges. This " & vbCrLf & _
            "is the count of values in each range:" & vbCrLf, _
            runCount, distGroupCount)
        Console.WriteLine("{0,21}{1,10}{2,20}{3,10}", _
            "Integer Range", "Count", "Double Range", "Count")
        Console.WriteLine("{0,21}{1,10}{2,20}{3,10}", _
            "-------------", "-----", "------------", "-----")
            
        ' Generate random integers and doubles, and then count 
        ' them by group.
        For i = 0 To runCount - 1
            intCounts(Fix(CDbl(randObj.Next()) / _
                intGroupSize)) += 1
            realCounts(Fix(randObj.NextDouble() * _
                CDbl(distGroupCount))) += 1
        Next i
            
        ' Display the count of each group.
        For i = 0 To distGroupCount - 1
            Console.WriteLine( _
                "{0,10}-{1,10}{2,10:N0}{3,12:N5}-{4,7:N5}{5,10:N0}", _
                Fix(CDbl(i) * intGroupSize), _
                Fix(CDbl(i + 1) * intGroupSize - 1.0), _
                intCounts(i), _
                CDbl(i) / CDbl(distGroupCount), _
                CDbl(i + 1) / CDbl(distGroupCount), _
                realCounts(i))
        Next i
    End Sub
End Module 
' This example of Random.Sample() generates output similar to the following:
'
'    The derived RandomProportional class overrides the Sample method to
'    generate random numbers in the range [0.0, 1.0]. The distribution
'    of the numbers is proportional to their numeric values. For example,
'    numbers are generated in the vicinity of 0.75 with three times
'    the probability of those generated near 0.25.
'    
'    Random doubles generated with the NextDouble() method:
'    
'      0.28377004  0.75920598  0.33430371  0.66720626  0.97080243  0.27353772
'      0.17787962  0.54618410  0.08145080  0.56286100  0.99002910  0.64898614
'      0.27673277  0.99455281  0.93778966  0.76162002  0.70533771  0.44375798
'      0.55939883  0.87383136  0.66465779  0.77392566  0.42393411  0.82409159
'    
'    Random integers generated with the Next() method:
'    
'      1364479914  1230312341  1657373812  1526222928   988564704   700078020
'      1801013705  1541517421  1146312560   338318389  1558995993  2027260859
'       884520932  1320070465   570200106  1027684711   943035246  2088689333
'       630809089  1705728475  2140787648  2097858166  1863010875  1386804198
'    
'    To demonstrate the proportional distribution, 1,000,000 random
'    integers and doubles are grouped into 10 equal value ranges. This
'    is the count of values in each range:
'    
'            Integer Range     Count        Double Range     Count
'            -------------     -----        ------------     -----
'             0- 214748363     9,892     0.00000-0.10000     9,928
'     214748364- 429496728    30,341     0.10000-0.20000    30,101
'     429496729- 644245093    49,958     0.20000-0.30000    49,964
'     644245094- 858993458    70,099     0.30000-0.40000    70,213
'     858993459-1073741823    90,801     0.40000-0.50000    89,553
'    1073741824-1288490187   109,699     0.50000-0.60000   109,427
'    1288490188-1503238552   129,438     0.60000-0.70000   130,339
'    1503238553-1717986917   149,886     0.70000-0.80000   150,000
'    1717986918-1932735282   170,338     0.80000-0.90000   170,128
'    1932735283-2147483647   189,548     0.90000-1.00000   190,347

설명

다른 임의 분포 또는 난수 생성기 원칙을 생성 하려면 클래스에서 클래스를 파생 시키고 Random 메서드를 재정의 Sample 합니다.To produce a different random distribution or a different random number generator principle, derive a class from the Random class and override the Sample method.

중요

Sample메서드는 protected Random 클래스 및 해당 파생 클래스 내 에서만 액세스할 수 있음을 의미 하는입니다.The Sample method is protected, which means that it is accessible only within the Random class and its derived classes. 인스턴스에서 0과 1 사이의 난수를 생성 하려면 메서드를 Random 호출 NextDouble 합니다.To generate a random number between 0 and 1 from a Random instance, call the NextDouble method.

상속자 참고

.NET Framework 버전 2.0부터에서 클래스를 파생 시키고 메서드를 재정의 하는 경우 Random Sample() 메서드의 파생 클래스 구현에서 제공 하는 배포는 Sample() 다음 메서드의 기본 클래스 구현에 대 한 호출에서 사용 되지 않습니다.Starting with the .NET Framework version 2.0, if you derive a class from Random and override the Sample() method, the distribution provided by the derived class implementation of the Sample() method is not used in calls to the base class implementation of the following methods: - NextBytes(Byte[]) 메서드- The NextBytes(Byte[]) method.

- Next() 메서드- The Next() method.

- Next(Int32, Int32) ( maxValue - minValue )가 보다 큰 MaxValue 경우 메서드- The Next(Int32, Int32) method, if (maxValue - minValue) is greater than MaxValue.

대신 기본 클래스에서 제공 하는 균일 한 배포가 Random 사용 됩니다.Instead, the uniform distribution provided by the base Random class is used. 이 동작은 클래스의 전체 성능을 향상 시킵니다 Random .This behavior improves the overall performance of the Random class. 파생 클래스에서 메서드의 구현을 호출 하도록이 동작을 수정 하려면 Sample() 이러한 세 멤버의 동작도 재정의 해야 합니다.To modify this behavior to call the implementation of the Sample() method in the derived class, you must also override the behavior of these three members. 예제에서는 그림을 제공합니다.The example provides an illustration.

적용 대상

추가 정보