0

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?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Martin
  • 97
  • 1
  • 6
  • I dont follow. The numbers given from `Random` are always _uniformly distributed_ between the given range. In your case, the range of all existing floats. So `nextFloat()` will give you any `float`, all with approximately the same chance. Please be more precise and explain exactly what you want, possibly with examples. – Zabuzard Feb 11 '21 at 22:56
  • Have you considered using `Object.hashCode()`? – pjs Feb 12 '21 at 00:14
  • NextFloat() gives you a float from 0 to almost 1. The random number generator is seeded with x. – NomadMaker Feb 12 '21 at 00:34
  • See also: https://stackoverflow.com/questions/64908600/does-randomstringutils-create-a-deterministic-or-reproducible-sequence/64909843#64909843 – Peter O. Feb 12 '21 at 00:40

1 Answers1

0

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);
}
Evan Darke
  • 604
  • 4
  • 7
  • Thanks for the answer, I wonder, how to make f return a value in the range [0,1)? For python I found this https://stackoverflow.com/q/40351791/5913493 – Martin Feb 12 '21 at 13:41
  • @Martin Once you get a random int from a hash, just divide it by Integer.MAX_VALUE to get a value in range [-1, 1]. At that point add 1 to get a value in [0, 2] and divide by 2 to get a value in [0, 1] – Evan Darke Feb 12 '21 at 16:54