开发者

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 curre开发者_运维知识库ntly 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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜