Skip to content

Generate a deterministic random number from any number

From a number x, I want a function to get a random number y, uniformly distributed. For same x, the function should return same y.

I tried:

float func(int x) {
  return new Random(x).nextFloat();
}

but apparently only the sequence of numbers provided by a seeded Random is uniformly distributed, not first values. Is this possible?

Answer

First, note that both int and float are 32bit datatypes in Java. So what you’re asking for is essentially a good hash function. If you want your random function to be 1:1, then this becomes a psuedomrandom permutation. So pick your favorite hash function and then reinterpret the bits as a float (not a cast)

public float f(x) {
   // Pick your favorite hash function here
   int hash = (int)(x * 2654435761L) // Fibonacci hash
   return Float.intBitsToFloat(hash);
}