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





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

Elena said...

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

Petr said...

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

Digital Art Gallery said...

Thank you, this help me on one project :)