C#/XNA pseudo-Random number creation
The c#/XNA process for creating random numbers is pretty quick and easy, however, it is quite possibly the worst distributing random number generator I have ever seen. Is there a better method that is easy to implement for c#/XNA?
rand.Next() just doesn开发者_高级运维't suit my needs.
from:
static private Random rand = new Random();
I randomly place objects, all over my program. sometimes 10, sometimes 200.
When calling for random objects (the x val and y val are both random on a 2d plane), they group. The generation code is clean and calls them good, iterated cleanly and pulls a new random number with each value. But they group, noticeably bad, which isn't very good with random numbers after all. I'm intermediate skill with c#, I crossed over from as3, which seemed to handle randomness better.
I am well-aware that they are pseudo random, but C# on a windows system, the grouping is grotesque.
Can you use System.Security.Cryptography.RandomNumberGenerator from XNA?
var rand = RandomNumberGenerator.Create();
byte[] bytes = new byte[4];
rand.GetBytes(bytes);
int next = BitConverter.ToInt32(bytes, 0);
To get a value within a min/max range:
static RandomNumberGenerator _rand = RandomNumberGenerator.Create();
static int RandomNext(int min, int max)
{
if (min > max) throw new ArgumentOutOfRangeException("min");
byte[] bytes = new byte[4];
_rand.GetBytes(bytes);
uint next = BitConverter.ToUInt32(bytes, 0);
int range = max - min;
return (int)((next % range) + min);
}
For my project I use simple XOR algorythm. I don't know how good it distributes numbers, but it is easy to implement:
http://www.codeproject.com/KB/cs/fastrandom.aspx
It may also depend on how you're using System.Random
. As a general rule, it is not a good idea to create new instances of Random
over and over, as Random
objects created at about the same time will very likely be seeded with the same random number (by default, time is used as the seed.) Instead, create a single instance of Random and use just that instance throughout your program.
Unless the goal is security, which is probably not the case here, you will be better off just using System.Random
.
精彩评论