Randomly generated values are not really random - c#

I am making a simple game in C# and using Random class to generate a random number every 2 seconds, but it gives numbers that I can guess in advance because it increments by a certain number each time.
private int RandomNumber;
//This Timer function runs every 2 seconds
private void TmrGenerateRandomNum(object sender, EventArgs e)
{
Random r = new Random();
RandomNumber = r.Next(50, 200); //Trying to get random values between 50 and 200
Label1.Text = RandomNumber.ToString();
}
This is literally the only code I have, and I am displaying the value each time through Label1. The problem is, for example, if I first get 52, the next "randomly"-generated value is 71 or 72, and the next one is 91 or 92, and the next one is 111 or 112. As you can see, it is incrementing by 20ish. Then it suddenly gets a real random value again like, say, 163. But then the next generated number is 183, again incremented by 20. Since 183+20 exceeds the range, it gets a real random value again, say 83. But the next number generated is again 103, or 104, and then 123 or 124...
This is not "Random" because you can tell around what number the next one is going to be... and this is driving me crazy.
Do you know why it does this, and is there a fix for this?

Random numbers use a seedvalue to start the sequence. If you give nothing, it takes to current datetime.now value. if you supply the same value (like 3842) you will get the same sequence of random values guaranteed. Your series seemed to be very closely related so you see the same values. All this can be read in the documentation on msdn, see Instantiate pseudo random :
Instantiating the random number generator
You instantiate the random number generator by providing a seed value (a starting value for the pseudo-random number generation algorithm) to a Random class constructor. You can supply the seed value either explicitly or implicitly:
The Random(Int32) constructor uses an explicit seed value that you supply.
The Random() constructor uses the system clock to provide a seed value. This is the most common way of instantiating the random number generator.
If the same seed is used for separate Random objects, they will generate the same series of random numbers. This can be useful for creating a test suite that processes random values, or for replaying games that derive their data from random numbers. However, note that Random objects in processes running under different versions of the .NET Framework may return different series of random numbers even if they're instantiated with identical seed values.
Source: https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx#Instantiate
You find more information and even methods to "better" cryptographical random methods linked above the source I cited.

While true random numbers are relatively difficult to generate, you should be able to get much better results than you are. The problem you're likely having right now, as suggested by comments, is that you should not be "starting over" every time the function is called. As a test, you can try passing some value like 5 as a parameter to the Random constructor. Then you will notice your results are really not random. To fix this, as the comments suggest, you should move the construction of the Random object somewhere global so that the randomness can "build" on itself over time instead of always being reset. Once you confirm that you can get different values with repeated calls, then remove the parameter to the Random constructor so that you don't get the same sequence of random numbers every time you restart your program.

More of an in-depth explanation:
Basically, it's pretty much impossible to generate truly random values in a computer, all of the random values you get are pseudo random and are based off of values like:
User input, like how many keys were pressed in the last 2 minuts
Memory usage, how many KB of memory is being used at this very moment
The most common one: Using the current time in mili seconds to generate a "seed" that's used to generate a series of numbers that are mathematical as randomized as possible
This is where the problem comes from. For example, if you were to have the following code
Random r1 = new Random();
Random r2 = new Random();
Console.WriteLine(r1.next())
Console.WriteLine(r2.next())
Miraculously, you will always get the same number from r1 and r2 despite them being two separate instances. It's because the code block is execute in a time window of <1 ms, which gives these two random number generators the same seed, thus they will generate the same list of numbers.
In your case, the number generator is instantiated every 2 seconds, thus they get an incrementing seed. It's hard to say if that will result in an incrementing starting number, but it might be a start.
So instead, try initializing a single Random() and always call the .next() function on it, and you should be getting a much more random list of numbers

The best you can do is use a CPRNG or Cryptograph Psudo Random Number Generator, it does not need to be seeded by tyhe user and in generally continnualy updates with system events.
To generate a cryptographically secure random number use the RNGCryptoServiceProvider class or derive a class from System.Security.Cryptography.RandomNumberGenerator.
See MSDN Random Class.

Related

Not jumping into code while not debugging [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 3 years ago.
for (int i = 1; i < 10; i++)
{
number = randomNumber();
if (!straightLine.Contains(number))
{
straightLine.Add(number);
}
}
public static int randomNumber()
{
Random random = new Random();
return random.Next(1, 100);
}
when I debug it works fine but when I run the program it gets 1 random number and that's it. so the problem is that the random Number method is only called once (when I don't debug then it calls it every time)
what can I do?
germi's answer is slightly misleading as it implies that any repeated instantiation of a new Random will produce the same sequence of values. This isn't quite correct, because your debug code works as you expect.
The documentation for Random says that the Random number generator is seeded from the system clock if you dont pass a seed value. https://learn.microsoft.com/en-us/dotnet/api/system.random.-ctor?view=netframework-4.8
The reason it works in debug is that debugging code is very slow (you're literally taking hundreds of milliseconds to step through the code a line at a time) and the clock has time to change in between runs of the loop.
When your code is run at full speed it runs so quickly that the system clock simply won't have changed to a new milliseconds value, so your repeated making of a new Random will result in it being seeded with the same value from the clock
If you were to insert some delay in the code such as Thread.Sleep(1000) in the loop then it would work. If you were to run the loop a million times it would take long enough to work through that the clock would eventually change - a million iterations might take long enough for a small handful of values to come out of the Random
The recommendation for a solution is sound though; make one new Random somewhere outside of the loop and then repeatedly call it. You could also seed the Random with something that is unique each time (like the value of i), though you should bear in mind that providing a particular seed will guarantee that the same random number comes out of it when you call Next. In some contexts this is useful, because you might want a situation where you can provide a certain value and then see the same sequence of random numbers emerge. The main thing to be mindful of is that by default the Random starts it's sequence based on the clock; two different computers with different time settings can theoretically produce the same random numbers if their clocks are reading the same at the moment the Random is created.
Repeatedly instantiating a new Random instance will lead to the same number being generated, since the seed will be the same.
The solution is to have one instance of Random in the class that generates the values:
var random = new Random();
for (int i = 1; i < 10; i++)
{
number = random.Next(1,100);
if (!straightLine.Contains(number))
{
straightLine.Add(number);
}
}
Note that this behavior only exists in .NET Framework, .NET Core will produce different values even across multiple Random instances created in quick succession.

Why Random makes same selection always? [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 9 years ago.
When I executes the following code I'm getting the same color selected always.
static void Main(string[] args)
{
string[] Colors = new string[10] { "Red", "Yellow", "Green", "Blue", "Purple", "White", "violet", "orange", "indigo", "blue" };
for (int i = 0; i < 13; i++)
{
Random rnd = new Random();
int code = rnd.Next(0, 9);
string Color = Colors[code];
Console.WriteLine(Color);
}
Console.ReadLine();
}
But if ` Random rnd = new Random();' is created outside the loop, then the result is unique. If the loop executes in faster rate then the output will be the same. Suppose I do some Database insert operation in the for loop the result will be a different one (a random one)(step by step execution using break points will also result random selection).
Is it really impossible to supply different seeds for such a small duration?
Random uses current time as a seed. When you create it in loop, it happens so fast that time stays the same for every creation. So seed is the same, and values, generated by Random will be the same too.
Try make random object a static member:
private static Random rnd = new Random();
This prevents building several random objects with a same seed (current time), and prevents producing a same sequence of numbers.
Your loop initializes a new instance of Random with the same seed (current time) upon each iteration. Each instance contains a sequence of various random numbers. The code uses the first number from the sequence, and after the iteration is finished the random object is thrown away, and a new Random object is instantiated. Since the code has been run quite fast, the next random object is created at the same time as the previous one, therefore it has the same seed as that one. The new object contains a sequence of various numbers, but the sequence is the same as the previous one (i.e., they have a same first number, second number, and so forth). Again the code uses the first number from the very same sequence, which results in repetitive numbers.
If you make the Random object a static member, the random sequence is created once, and the code will use the next number (not always the first number) of that sequence, hence you will iterate through the sequence of various random numbers.
If you don't want to make the random object a static member, try to feed its constructor a unique seed. You can make use of your loop variable for this purpose.
If you don't provide a seed, Random will use Environment.TickCount for a seed. In a short loop like this, it's entirely possible that the the whole loop is executed in one tick. So the seed is the same every time, hence your "random" number is, too.
Just use the same random object for the entire loop.
Random is not random in computer programming ;) You can make it "more" random by including a seed or by having a static object containing the random :)
you need to keep the same random object for the reason below:
Pseudo-random numbers are chosen with equal probability from a finite set of numbers. The chosen numbers are not completely random because a definite mathematical algorithm is used to select them, but they are sufficiently random for practical purposes.
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated.
http://msdn.microsoft.com/en-gb/library/system.random.aspx

How should i be generating a random number between 0 and up to 2? BCL Random is not random

How should i be generating a random number between 0 and up to 2?
I am currently using a private static readonly Random object and call _random.Next(0, 2) BUT the values are not random ... I see sequences of 0,0,0,1,1,0,0,0,,1,1,1
The below is clearly not random. How should I be doing this?
Thanks a lot
If you mean you want random numbers 0 or 1, then what you’re doing is already correct.
If you want numbers 0, 1 or 2, then you need to write _random.Next(0, 3).
You are already doing it the right way (as long as your requirements for pseudo-random numbers doesn't include cryptographic security).
The problem is that randomness is statistically determined (using math), not intuitively determined (using your eyes).
For example, even if your random number sequence is uniformly random, given an infinite sequence of random numbers, you will still see one-hundred-thousand 1s in a row.
See this Wikipedia article on Pseudorandom Number Generators
If you are trying to get the numbers "0, 1, 2", then you may need to change your call to random.Next(0, 3). If you indeed only want 0 and 1, then leave it as it is.
Also, if you are creating instances of Random in multiple places in your code, you may get identical seeds, so will get identical sequences of random numbers. One way to avoid this would be to reuse the instance of the Random class between those two pieces of code, rather than creating new instances.
If you initialize Random with the same seed, you will get the same sequence of numbers. That's why it might be a good idea to use a time-based seed:
Random _random = new Random(DateTime.UtcNow.Millisecond);
Also, note that the upper bound in Next is exclusive. That means that Next(0, 2) will always return only 0 or 1 (but that might be what you wanted; somewhat unclear to me from the question).
The maxValue is "upto-and-not-included". If you wish to include 2, just write _random.Next(0,3)

C# Random generation

I have just passed this article online:
C# Corner and C# Corner and his article (a software developer with over 13 years of experience) recommended using System.Random as follows:
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
Isn't that would give him the same number every time ??
Edit:
So my question will become: How does Random choose its seed? a constant or current time value?
Thanks
You should only initialize the seed once and then reuse it:
private Random random = new Random();
private int RandomNumber(int min, int max)
{
return random.Next(min, max);
}
It will give the same result when the method will be called often between short time intervals. This is because the Randoms seed is initialized with the current time value.
This is also the reason why many people have problem of kind that random is not random at all.
BTW it is not Math.Random but System.Random
Following your edit, here is some information on how random is initialized. The information comes from the link above.
The random number generation starts
from a seed value. If the same seed is
used repeatedly, the same series of
numbers is generated. One way to
produce different sequences is to make
the seed value time-dependent, thereby
producing a different series with each
new instance of Random. By default,
the parameterless constructor of the
Random class uses the system clock to
generate its seed value, while its
parameterized constructor can take an
Int32 value based on the number of
ticks in the current time. However,
because the clock has finite
resolution, using the parameterless
constructor to create different Random
objects in close succession creates
random number generators that produce
identical sequences of random numbers.
No because new Random() will init with current time as a seed. That said you should still preserve instance of the random and reuse it.
Maybe. Random created without an explicit seed seeds itself based on current time. If you called RandomNumber rapidly enough you'd get the same number occasionally.
Your intuition is correct, however. It's dumb to create a new Random object every time you need a new number. You should create a single instance and use it.

How random is Random.Next()?

I have been doing some testing on the Random class and I have used the following code:
while (x++ <= 5000000)
{
y = rnd.Next(1, 5000000);
if (!data.Contains(y))
data.Add(y);
else
{
Console.WriteLine("Cycle {2}: Repetation found for number {0} after {1} iteration", y, x, i);
break;
}
}
I kept changing the rnd max limit (i.e. 5000000) and I changed the number of iterations and I got the following result:
1) if y = rnd.Next(1, 5000) : The average is between 80 to 110 iterations
2) if y = rnd.Next(1, 5000000) : The average is between 2000 to 4000 iterations
3) if y = rnd.Next(1, int.MaxValue) : The average is between 40,000 to 80,000 iterations.
Why am I getting these averages, i.e. out of 10 times I checked for each value, 80% of the time I get within this average range. I dont think we can call it near to being Random.
What can I do to get a fairly random number.
You are not testing for cycles. You are testing for how long it takes to get a random number you've had before. That's completely different. Your figures are spot on for testing how long it takes to get a random number you had before. Look in wikipedia under "the birthday paradox" for a chart of the probability of getting a collision after a certain number of iterations.
Coincidentally, last week I wrote a blog article about this exact subject. It'll go live on March 22nd; see my blog then for details.
If what you want to test for is the cycle length of a pseudo-random number generator then you need to look for not a number you've had before, but rather, a lengthy exact sequence of numbers that you've had before. There are a number of interesting ways to do that, but it's probably easier for me to just tell you: the cycle length of Random is a few billion, so you are unlikely to be able to write a program that discovers that fact. You'd have to store a lot of numbers.
However, cycle length is not the only measure of quality of a pseudo-random number generator. Remember, PRNGs are not random, they are predictable, and therefore you have to think very carefully about what your metric for "randomness" is.
Give us more details: why do you care how "random" Random is? What application are you using it for that you care? What aspects of randomness are important to you?
You are assuming that the randomness is better if numbers are not repeated. That is not true.
Real randomness doesn't have a memory. When you pick the next number, the chance to get the same number again is just as high as any other number in the range.
If you roll a dice and get a six, then roll the dice again, there is no less chance to get a six again. If you happen to get two sixes in a row, that doesn't mean that the dice is broken.
The randomness in the Random class it of course not perfect, but that is not what your test reveals. It simply shows a phenomenon that you get with every random number generator, even if actually creates real random numbers and not just pseudo-random numbers.
You are judging randomness by repeat pairs, which isn't the best test for randomness. The repeats you see are akin to the birthday paradox: http://en.wikipedia.org/wiki/Birthday_problem, where a repeat event can occur with a small sample size if you are not looking for a specific event.
Per the documentation at http://msdn.microsoft.com/en-us/library/system.random.aspx
To generate a cryptographically secure
random number suitable for creating a
random password, for example, use a
class derived from
System.Security.Cryptography..::.RandomNumberGenerator
such as
System.Security.Cryptography..::.RNGCryptoServiceProvider.
A computer can't generate a real random number.
if You need a real random number (David gave you the best option from dot net framework)
you need an external random source.

Categories