How do I go about producing random numbers within a range?
Asked
Active
Viewed 5.6e+01k times
7 Answers
565
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

TylerH
- 20,799
- 66
- 75
- 101

Adriaan Stander
- 162,879
- 31
- 289
- 284
-
38Just 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;` – Tom Heard Oct 28 '13 at 20:03
-
3Or a simplified double generator in the range of -1.0 and 1.0: Double randDoubleY = new Random().Next(-100, 100) / 100.0D; – BoiseBaked Dec 15 '18 at 21:29
-
1`Random()` uses a time-dependent seed, but writing that out explicitly is better for readability. – Evgeni Sergeev Mar 10 '19 at 05:50
78
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

Vishal Kiri
- 1,248
- 1
- 12
- 24
-
This seems to just repeat the existing answers from 5 years prior (use `Random()` and `.Next()`). – TylerH Jul 08 '22 at 21:00
43
Something like:
var rnd = new Random(DateTime.Now.Millisecond);
int ticks = rnd.Next(0, 3000);

Kasun Kodagoda
- 3,956
- 5
- 31
- 54

ozczecho
- 8,649
- 8
- 36
- 42
-
2
-
2You 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(). – Mike M Dec 28 '17 at 00:05
-
22`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. – John McDonald Sep 13 '18 at 14:32
-
1@JohnMcDonald, you are correct. Just to be precise, it is initialized with `Environment.TickCount`. – Parag Meshram Apr 18 '20 at 10:41
-
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. – Moses Dec 07 '21 at 02:16
-
Random.Next(MinValue, MaxValue) is not a safe method. It returned many duplicate values when i tried to generate 100 random numbers between 60000 and 63000. – Syed Irfan Ahmad Mar 02 '22 at 08:58
16
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)

Darrel K.
- 1,611
- 18
- 28
-
2Formula should be in the following way: `return new Random().NextDouble() * (maxNumber - minNumber) + minNumber;` – Frank Sebastià Feb 11 '19 at 16:30
-
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 Jan 21 '22 at 15:39
-
@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. – Darrel K. Jan 24 '22 at 04:20
-
-
@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. – Darrel K. Sep 05 '22 at 09:43
15
Use:
Random r = new Random();
int x= r.Next(10);//Max range

Jeffrey Blake
- 9,659
- 6
- 43
- 65

Kay
- 702
- 7
- 16
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);

Konstantin Gindemit
- 382
- 1
- 4
- 10
5
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

Community
- 1
- 1

Ohad Schneider
- 36,600
- 15
- 168
- 198