January 14, 2010

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


'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

3 Responses to "Generate a Random Floating Point Number between two Numbers"
  1. Elena said...
    January 27, 2010 8:37 AM

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

  2. Petr said...
    March 31, 2010 12:17 AM

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

  3. Digital Art Gallery said...
    November 11, 2010 10:42 AM

    Thank you, this help me on one project :)

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions