I know that unity uses pseudorandom to make it faster, but I am finding random.range to not work well. I have four random number generators, all with the same range, and they all print their number at the same time. However, it is common for all four to output the same number, yet the range is 0 to 10. Any thoughts on this?
[Edit] I may have to be forced to close this question, I didn’t set the seed manually. Maybe my computer is going insane, or I am, but no one else can reproduce the problem so I guess it isn’t worh it to answer this.
I did a little test to show how often Random.Range() generates the same random numbers:
public class Test : MonoBehaviour {
int[] result = new int[5];
int total = 0;
// Use this for initialization
void Start () {
while (total != 1000) {
int[] ints = new int[4];
int[] control = new int[10];
string output = "";
for (int i = 0; i < 4; i++) {
ints *= Random.Range (0, 10);*
_ control [ints ] += 1;_ _ output += ints + “-”;
* } for (int i = 0; i < 10; i++) { result [control ]++; } total++; Debug.Log (output); } for (int i = 1; i < 5; i++) { Debug.Log ((i) + " Time(s): " + result ); } }*_
* // Update is called once per frame* * void Update () {*
* }* } One test of mine gave the following result: 1 Time(s): 2926 2 Time(s): 477 3 Time(s): 40 4 Time(s): 0 This means: in 1000 generated Quadrupels (4 numbers) there were 477 duplicated numbers and 40 times a number was in there 3 times. I have the feeling that this is not suspicious, but I failed to quickly find a formula to prove these probabilities.
Even with a truly random set of numbers, you will get two random numbers that are the same very often with a small range. The way statistics works, with a range of N you will not get the same result once out of every N-squared times as you might initially intuit (every 100 times in your case). Rather, you will get the same results approximately once every N times (or once every 10 times, in your case).
Basically, you should get the same results with 2 rolls, and it should happen often enough to be noticeable. If you do something fancy to make that happen less, then you are actually reducing the randomness.
If you roll physical dice on a table, you will find similar occurrences. While role playing with some friends one time, I was rolling a 20-sided die and I got 2 twenties in a row then a 19 on the third roll. And sometimes in board games it seems like the dice are unfair. True randomness can seem that way sometimes, but if you average it all out over thousands of rolls it will all average out and the “magic” disappears.