Generate a Random Floating Point Number between two Numbers

The Random.NextDouble() method returns a random number between 0.0 and 1.0. However what if you want to specify the upper and lower limits and then generate a random double number? Here’s some code I had written a couple of months ago to generate a random double number between two numbers:

C#

class Program
{
static void Main(string[] args)
{
double dr = GenRand(1.0, 20.0);
Console.WriteLine(dr);
Console.ReadLine();
}

static double GenRand(double one, double two)
{
Random rand = new Random();
return one + rand.NextDouble() * (two - one);
}
}

VB.NET

Friend Class Program
Sub Main(ByVal args() As String)
Dim dr As Double = GenRand(1.0, 20.0)
Console.WriteLine(dr)
Console.ReadLine()
End Sub

Shared Function
GenRand(ByVal one As Double, ByVal two As Double) As Double
Dim
rand As New Random()
Return one + rand.NextDouble() * (two - one)
End Function
End Class

3 comments:

  1. Thank you for interesting information. I was searching this information for a long time.

    ReplyDelete
  2. It's very interesting article. Thank you for information.

    ReplyDelete
  3. Thank you, this help me on one project :)

    ReplyDelete