How do I go about producing random numbers within a range?
9 Answers
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
3 Comments
double rDouble = (r.NextDouble()*2)-1.0;Random() uses a time-dependent seed, but writing that out explicitly is better for readability.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
Random() and .Next()).Something like:
var rnd = new Random(DateTime.Now.Millisecond); int ticks = rnd.Next(0, 3000); 6 Comments
DateTime.Now.Millisecond?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.Environment.TickCount.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) 5 Comments
return new Random().NextDouble() * (maxNumber - minNumber) + minNumber;Use:
Random r = new Random(); int x = r.Next(10); // Max range 2 Comments
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
Aside from the Random Class, which generates integers and doubles, consider:
Stack Overflow question Generation of (pseudo) random constrained values of (U)Int64 and Decimal
Comments
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 from0to less thanInt32.MaxValue. To generate a random number whose value ranges from 0 to some other positive number, use theRandom.Next(Int32)method overload. To generate a random number within a different range, use theRandom.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
(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; }