0

I need a method similar to nextInt(int bound) of Java Random Class for long data type. Here is my implementation:

   static long randomLong(Random rNumber, long bound)
   {
      long z = rNumber.nextLong();

      return (z % bound);
   }

Where rNumber is initialized from the calling method as,

Random rNumber = new Random();

My question is, does this implementation ensures a pseudorandom, uniformly distributed long value between 0 (inclusive) and the bound (exclusive) ?

User_67128
  • 1,230
  • 8
  • 21
  • 1
    No. Some numbers are more likely, because modulo is not uniform if bound does not divide Long.MAX_VALUE - Long.MIN_VALUE. – Johannes Kuhn Oct 25 '19 at 19:24
  • 4
    why don't you use `ThreadLocalRandom.current().nextLong(origin, bound)` – Ryuzaki L Oct 25 '19 at 19:25
  • 1
    Take a look at the implementation of the equivalent method for `int`. It may not show you how to do it for long, but it will hopefully convince you that it isn't this simple. – Andy Turner Oct 25 '19 at 19:26
  • ThreadLocalRandom.current().nextLong(origin, bound) will serve my need. Thanks @Deadpool. – User_67128 Oct 25 '19 at 19:46

0 Answers0