mercredi 29 avril 2020

Make a Psudo Random Number Generator Based on Many Inputs Javascript

The current project that I am working on involves a multidimensional world, which can have many more than just 3 dimensions, and need to get values for each position of that world. I already have a good Pseudo Random Number Generator (PRNG) that takes a seed and a single value. What I need is to have a function that can use as many inputs as are provided, and return a value based on those positions. The PRNG also should not have to rely on its previous values to determine it's next state, and should work (as close as possible to) the same on any browser or system.

My current PRNG, works very well for 1 input (xxHash):

function random(seed, x) {
    /* mix around the bits in x: */
    x = x * 3266489917 + 374761393;
    x = (x << 17) | (x >> 15);

    /* mix around the bits in y and mix those into x: */
    x += seed * 3266489917;

    /* Give x a good stir: */
    x *= 668265263;
    x ^= x >> 15;
    x *= 2246822519;
    x ^= x >> 13;
    x *= 3266489917;
    x ^= x >> 16;

    /* trim the result and scale it to a float in [0,1): */
    return (x & 0x00ffffff) * (1 / 0x1000000);
}

I tried adding more parameters and mixing them up, but that didn't go so well (Below):

function rand(seed, ...prams){
    let x = prams[0] + seed;

    x = x * 3266489917 + 374761393;
    x = (x << 17) | (x >> 15);

    /* mix around the bits in y and mix those into x: */
    for(let i =1; i< prams.length; i++){
        prams[i] *= seed;
        x *= prams[i] * 3266489917
    }

    /* Give x a good stir: */
    x *= 668265263;
    x ^= x >> 15;
    x *= 2246822519;
    x ^= x >> 13;
    x *= 3266489917;
    x ^= x >> 16;



    /* trim the result and scale it to a float in [0,1): */

    let val = ((x & 0x00ffffff) * (1.0 / 0x1000000))
     return val;
}

This one didn't return any errors, but if the inputs were in a different order, the value was the same, which means that rand(seed, 5, 1, 1) === rand(seed, 1, 5, 1) === rand(seed, 1, 1, 5) , Which is not great behavior.

I need a function random(seed, ...position) that will generate a pseudo random number between 0 and 1 that is affected by both the order and all the values in the position array.




Aucun commentaire:

Enregistrer un commentaire