Random not random enough

Hello,

When I create several objects of the same type in a loop (let’s say a treasure box is exploding and coins fly out), I’m setting their direction and speed using random functions, but they are not random enough. Many times at least 2 of them have the exact same “random” properties set.
I also tried the method on this site which is somewhat better, but still not good enough:
https://scottlilly.com/create-better-random-numbers-in-c/

Any tricks to get around this, a better random generator or maybe a better seed?

Thanks

Are you creating a new random everytime you launch a projectile?

Have 1 global Random that you reference and gets instantiated once.

2 Likes

Hello Lajbert
I never had this problem before.
I agree with Boot , just déclare only one Random() instance and use NextDouble() each time you want a new random number , I think that will solve your issue.

See my sample code bellow :

Random RND = new Random();
for (int t = 0; t < NB; t++)
    {
       Px = (float)RND.NextDouble() * TerrainTextureMap.Width * Map.TileSize;
       Pz = (float)RND.NextDouble() * TerrainTextureMap.Height * Map.TileSize;
       Py = Map.GetHightPos(Px, Pz);
    }

I hope that will help you

Chris

1 Like

I’ll give this a try, thanks guys!

Have a quick read here

When you initialise a new random without giving it a seed it uses the system clock for a seed. If your initialising a new random in a tight loop you will get the same seed and the same values.

So only use one instance of random globally, or create a new instance before your loop.

If you want to have the same random sequence everytime give it the same seed (eg 1000)
Random random = new Random(1000)

1 Like

This is a common problem if you create a new random in a loop. The safest solution, as mentioned, is to create just one Random object for the whole project. That can get a little problematic if you need random numbers in several places and don’t want a global object. There are several ways to solve it, if that’s a concern you have, but whatever you do, make sure that you don’t create more than one Random object per second (with .NET, you might be able to get it down to 1/ms, or smaller, but 1/second is always safe).

If that still isn’t random enough, there is a ‘more random’ option in the Crypography Library

1 Like

And there is a common mistake of not using all the bits of the random number.

The number of times I have heard people bitching about the random number generator not being very random and they were doing something like

  int64 r = random.NextInt64();
  int x = (r&255);

Taking 64 bits of random data and reducing it to 8 bits.

The example above that uses random.NextDouble() is a much better idea.

1 Like

Thanks everyone.