390

How do I go about producing random numbers within a range?

0

9 Answers 9

598

You can try

//for integers Random r = new Random(); int rInt = r.Next(0, 100); //for doubles int range = 100; double rDouble = r.NextDouble()* range; 

Have a look at

Random Class, Random.Next Method (Int32, Int32) and Random.NextDouble Method

Sign up to request clarification or add additional context in comments.

3 Comments

Just to add a note, if you are using NextDouble() and don't want the lower bound to be zero. You multiply by the difference between the higher bound and the lower bound, then add the difference between the lower bound and zero. So for -1 to 1 double rDouble = (r.NextDouble()*2)-1.0;
Or a simplified double generator in the range of -1.0 and 1.0: Double randDoubleY = new Random().Next(-100, 100) / 100.0D;
Random() uses a time-dependent seed, but writing that out explicitly is better for readability.
83

Try below code.

Random rnd = new Random(); int month = rnd.Next(1, 13); // creates a number between 1 and 12 int dice = rnd.Next(1, 7); // creates a number between 1 and 6 int card = rnd.Next(52); // creates a number between 0 and 51 

4 Comments

This seems to just repeat the existing answers from 5 years prior (use Random() and .Next()).
@TylerH, yes but at least this explains that the lower bound is inclusive and the upper bound is exclusive. That's not something obvious, so the original example leaves it unclear if the actual random number range is from 0-100, 1-100, 0-99, or 1-99
Couldn't the top answer just have been edited? Thats kinda the point of editing.
I'm glad he provided this example, he is absolutely correct about the ambiguity of the lower and upper bounds in the other answers
44

Something like:

var rnd = new Random(DateTime.Now.Millisecond); int ticks = rnd.Next(0, 3000); 

6 Comments

for what is DateTime.Now.Millisecond?
You need to put something for it to start with...... the Random object simply does lots of math on the value you give, and does so in a way that each call of Next() on the same Random object will result in a value quite random to the previous call. To make the result more random across different Random objects , you start with a different number -- here, the DateTime.Now.Millisecond. If you put a constant, rather than a changing value, you would get the same results from .Next().
Random is already seeded with a system value, and Millisecond is only a number between 0 and 999. If this pair of lines were always together in code, there would only be 1000 possible values of rnd.Next due to the seed being reset each time. Same seed in, same random number out. I'd leave the manual seed out.
@JohnMcDonald, you are correct. Just to be precise, it is initialized with Environment.TickCount.
Thanks, it worked! I made it like this: var rnd = new Random(DateTime.Now.Millisecond + i); in the loop where "i" is incremental in the loop.
|
20

For future readers if you want a random number in a range use the following code:

public double GetRandomNumberInRange(Random random,double minNumber, double maxNumber) { return random.NextDouble() * (maxNumber - minNumber) + minNumber; } 

usage:

Random r = new Random(); double num1 = GetRandomNumberInRange(r, 50, 100) 

C# Random double between min and max

Code sample

5 Comments

Formula should be in the following way: return new Random().NextDouble() * (maxNumber - minNumber) + minNumber;
Never do this. DO NOT create a Random instance each time. ALWAYS reuse a Random instance when using repeatedly over time. I've seen code like the above work great while debugging (ie: slowly), but produce the same random numbers while running in production (ie: full speed). At the time, it was because creating two Random() instances in the same moment, they both produced the same random numbers. Think of it as the Random is being seeded by the current time, so if close enough, they will both have the same seed, and produce same numbers. Don't pull out your hair. Reuse your new Random.
@AAron, good point. Think the readers needs to know this yes. Would be a good idea to add the Random to a class variable or passing in an existing instance, so that it can be reused. Especially if you need it to be done multiple times in the same moment. It all depends where you want to use this code and how many times it will be executed.
Why should future readers use this answer rather than existing ones?
@TylerH, This is to get a random double in a range between two numbers. The code sample on the existing answer does not have a start of the range (for double values). It always starts at 0, where this method has a defined min and max value. Hope this answers your question and assit future readers.
15

Use:

Random r = new Random(); int x = r.Next(10); // Max range 

2 Comments

This does not specify a range.
You just do lower_value + r.Next(10) to get a random range.
10

Here is updated version from Darrelk answer. It is implemented using C# extension methods. It does not allocate memory (new Random()) every time this method is called.

public static class RandomExtensionMethods { public static double NextDoubleRange(this System.Random random, double minNumber, double maxNumber) { return random.NextDouble() * (maxNumber - minNumber) + minNumber; } } 

Usage (make sure to import the namespace that contain the RandomExtensionMethods class):

var random = new System.Random(); double rx = random.NextDoubleRange(0.0, 1.0); double ry = random.NextDoubleRange(0.0f, 1.0f); double vx = random.NextDoubleRange(-0.005f, 0.005f); double vy = random.NextDoubleRange(-0.005f, 0.005f); 

Comments

5

Aside from the Random Class, which generates integers and doubles, consider:

Comments

1

Two kinds of random numbers

There are two "kinds" of random numbers:

  • pseudo-random numbers
  • cryptographically secure random numbers

Both are based on a seed. For pseudo-random numbers that seed is easy to guess, as it is based on the CPU's clock, for cryptograhpically secure random numbers it is hard to guess making the numbers "truely" random i. e. unpredictable. If you want to know more about that in layman's terms please see the following answer on a different SO thread. For a more in-depth look and distinction see What is the difference between CSPRNG and PRNG? on the Cryptography StackExchange.

Depending on your use case you will want to choose one over the other. In general if you do something security-critical like generating some nonce you will want to use the cryptographically secure random numbers. On the other hand, if you need random numbers for example for a game you are better off using pseudo-random numbers.

Pseudo-random numbers

Pseudo-random numbers can be generated using the Random class. All you need to do is instantiate it and call the method Next(), which also has several overloads you will find useful

Random.Next() generates a random number whose value ranges from 0 to less than Int32.MaxValue. To generate a random number whose value ranges from 0 to some other positive number, use the Random.Next(Int32) method overload. To generate a random number within a different range, use the Random.Next(Int32, Int32) method overload.

Quoted from Microsoft Docs for Random.Next().

Example

using System; // Instantiate an instance of Random Random random = new(); // Generate pseudo-random number between 2 and 9 (upper bound is exclusive!) var randomNumber = random.Next(2, 10); 

>= .NET 6

Since .NET 6 Random also has a public static property Shared which gives you access to a shared (i. e. shared across all threads) instance of Random which is thread-safe. So typically you would just use that instance.

using System; // Generate pseudo-random number between 2 and 9 (upper bound is exclusive!) Random.Shared.Next(2, 10) 

Cryptographically secure random numbers

For cryptographically secure random numbers use RandomNumberGenerator and its GetInt32() method and its overloads:

Example

using System.Security.Cryptography; // Generate cryptographically secure random number between 2 and 9 (upper bound is exclusive!) var randomNumber = RandomNumberGenerator.GetInt32(2, 10); 

Comments

0

(this method using decimals, exluding maxValue)

 public static float NextFloatRange (Random r,float minValue,float maxValue) { float f1 = r.NextSingle()*(maxValue-minValue)+minValue; return f1; } public static double NextDoubleRange(Random r, double minValue, double maxValue) { double f1 = r.NextDouble() * (maxValue - minValue) + minValue; return f1; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.