Search code examples
javarandomsimplex

Generate random number between -1 and 1?


So I found this useful website with a lot of code and explanation to perlin and simplex noise. However, the code is written in a different language. I was able to rewrite most of it for java, however there is one function that 1. I don't understand, and 2. I don't know how to write it in java. The code is:

function IntNoise(32-bit integer: x)             

    x = (x<<13) ^ x;
    return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);    

  end IntNoise function

Again, I don't know what language it is written in. However, the author states that the function returns a random number between -1 and 1. Can someone explain what exactly the & symbol does? And why there are a bunch of seemingly random numbers? And is there a simple way to convert this to java?


Solution

  • The inner part hashes the number, the & and / turns this hash into a number between 0 and 2 so when you do 1 - (..) you get a number between -1 and 1.

    A Java way to get a random number between -1 and 1 is

    return Math.random() * 2 - 1;
    

    or if you need to use a seed

    return new Random(x).nextDouble() * 2 - 1;