C# Random NextDouble
Description
Random NextDouble
returns a random floating-point number
between 0.0 and 1.0.
Syntax
Random.NextDouble
has the following syntax.
public virtual double NextDouble()
Returns
Random.NextDouble
method returns A double-precision floating point number greater than or equal to 0.0, and
less than 1.0.
Example
The following example uses the NextDouble method to generate sequences of random doubles.
using System;/* ww w. jav a2 s. c o m*/
using System.Threading;
public class RandomObjectDemo
{
static void Main( )
{
Random randObj = new Random();
// Generate the first six random doubles.
for( int j = 0; j < 6; j++ )
Console.Write( " {0:F8} ", randObj.NextDouble( ) );
}
}
The code above generates the following result.
Example 2
The following example calls the NextDouble method to generate 100 random numbers and displays their frequency distribution.
using System;/* w w w . j a v a2 s .c o m*/
public class Example
{
public static void Main()
{
int[] frequency = new int[10];
double number;
Random rnd = new Random();
for (int ctr = 0; ctr <= 99; ctr++) {
number = rnd.NextDouble();
frequency[(int) Math.Floor(number*10)] ++;
}
Console.WriteLine("Distribution of Random Numbers:");
for (int ctr = frequency.GetLowerBound(0); ctr <= frequency.GetUpperBound(0); ctr++)
Console.WriteLine("0.{0}0-0.{0}9 {1}", ctr, frequency[ctr]);
}
}
The code above generates the following result.