سؤال

I'm tried to make some world generation mechanism using Math.random() whenever I needed something random, but then decided that I wanted it seed-based, so, given a seed, I changed all of the Math.random() to Math.sin(seed++)/2+0.5, hoping it would do the same thing, but would be the same if the seed was the same seed. Then someone made me notice that the sin wave hasn't got even distribution, and finally I saw why some of my code was working strangely. I was wondering if there was a simple fix, or if there isn't, another very simple seed based randomizer like this

هل كانت مفيدة؟

المحلول

So, I looked at your method, t1wc, and I found that it isn't actually evenly distributed. It is significantly more likely to spit out numbers near 0 or near 1 than it is to spit out numbers near 0.5, for example. This is just a consequence of the way that the sine function works.

Instead, you might try using a method called Blum Blum Shub (named after the authors of the original paper, wonderfully). It is evenly distributed and quite fast. Given a seed, it works as follows:

  1. Square the seed and put the result in a temporary variable (x).
  2. Take the mod of x base M.
  3. M is a product of two large primes.
  4. The value of x is a new seed to be used for future calculations.
  5. Return x/M as your pseudo-random number. It will be evenly distributed between 0 and 1.

Below is a simple implementation of a Blum Blum Shub:

var SeededRand = function(seed, mod1, mod2)
{
    return function()
    {
        seed = (seed*seed) % (mod1*mod2);
        return seed/(mod1*mod2);
    };
};

If you want to make a new random number generator, you just call:

var rand = SeededRand(seed, mod1, mod2);

Where seed is some initial seed (1234567890 works well), and mod1 and mod2 are some large primes (7247 and 7823 work well). rand is just a variable that I've defined to hold the output.

Now, to start getting random values, you just call:

rand();

Which will spit out a different value each time you run it.

If you have any questions, please ask!

نصائح أخرى

There is a very nice seed-based randomizing script already made. It can be found here.

ok guys, found out this is what I'm really looking for:

(((Math.sin(seed.value++)/2+0.5)*10000)%100)/100

It sends out even spreaded numbers, and I guess it's a lot simpler than any other number generator I've seen

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top