Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Random.Next ever stop being random?

Tags:

c#

.net

I need to create random numbers between 0 and upto 2 so I am using:

//field level
private static Random _random = new Random();

//used in a method
_random.Next(0, 2)

My question is: will the sequence ever repeat / stop been random? Should I recreate (_random = new Random();) every day?

like image 350
arkina Avatar asked Feb 25 '11 13:02

arkina


3 Answers

Your code is fine as it is.

You do not need to create a new Random object daily.

Note that Random is not truly random, but produces a pseudo-random result.

like image 132
Oded Avatar answered Nov 03 '22 23:11

Oded


If you check the 'remarks' section in the documentation you will find that System.Random is a pseudo-random generator.

This means in theory the sequence does eventually repeat. In practice it very much depends on what you're doing as to how much this matters. For example, the length of the sequence is such that no human will ever notice them repeating. On the otherhand, it's pretty useless for cryptography.

Edit to add: restarting daily won't make much difference. Either the pseudo-randomness is sufficient for you or you need to look into cryptographically secure way of generating random numbers.

like image 4
mavnn Avatar answered Nov 04 '22 01:11

mavnn


Math.Random returns a 32-bit signed integer, it will repeat on the 2^32'nd call if you dont reseed. If you DO reseed it will repeat itself sooner.

like image 2
Bernd Elkemann Avatar answered Nov 03 '22 23:11

Bernd Elkemann