Reputation: 16502
How do I go about producing random numbers within a range?
Upvotes: 386
Views: 614994
Reputation: 1
(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;
}
Upvotes: 0
Reputation: 9258
There are two "kinds" of 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 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 from0
to 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()
.
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);
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)
For cryptographically secure random numbers use RandomNumberGenerator
and its GetInt32()
method and its overloads:
using System.Security.Cryptography;
// Generate cryptographically secure random number between 2 and 9 (upper bound is exclusive!)
var randomNumber = RandomNumberGenerator.GetInt32(2, 10);
Upvotes: 1
Reputation: 1729
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
Upvotes: 20
Reputation: 166606
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
Upvotes: 596
Reputation: 437
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);
Upvotes: 10
Reputation: 1316
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
Upvotes: 83
Reputation: 38172
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
Upvotes: 5
Reputation: 8869
Something like:
var rnd = new Random(DateTime.Now.Millisecond);
int ticks = rnd.Next(0, 3000);
Upvotes: 44