a developer's notes – a semi-technical web development BLOG

November 19, 2013

A Random function to generate a random number

Filed under: C# — Duy Nguyen @ 11:17 am
Tags: , , , , ,
static public void GetRandomDoubleNumber()
{
	// You can do it all on one line like this:
	//double doubleStr = Math.Truncate((new Random().NextDouble()) * 100) / 100;

	Thread.Sleep(1);
	Random autoRand = new Random((int) DateTime.Now.Ticks & 0x0000FFFF); //passing in a unique 'seed' to produce different random numbers.
	
	// Use for doubles
	double dNumber = 0.0;
	double dmin = 0.01;  //inclusive lower bound 
	double dmax = 1; //exclusive upper bound
	dNumber = GenerateRandomDoubleNumber(autoRand, dmin, dmax);

	// Use for ints
	int inumber = 0;
	int iMin = 1;
	int iMax = 10;
	inumber = GenerateRandomIntNumber(autoRand, iMax, iMin);

}

static public double GenerateRandomDoubleNumber(Random randObj, double max, double min)
{
	double randomNumber = randObj.NextDouble() * (max - min) + min;
	return Math.Truncate(randomNumber * 100) / 100;
}

static public int GenerateRandomIntNumber(Random randObj, int max, int min)
{
	int randomNumber = randObj.Next(min, max);
	return randomNumber;
}


Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: