how random is Math.random() in java across differe

2019-03-18 23:36发布

问题:

I have a large distributed program across many different physical servers, each program spawns many threads, each thread use Math.random() in its operations to draw a piece from many common resource pools.

The goal is to utilize the pools evenly across all operations. Sometimes, it doesn't appear so random by looking at a snapshot on a resource pool to see which pieces it's getting at that instant (it might actually be, but it's hard to measure and find out for sure).

Is there something that's better than Math.random() and performs just as good (not much worse at least)?

回答1:

Math.random() is based on java.util.Random, which is based on a linear congruential generator. That means its randomness is not perfect, but good enough for most tasks, and it sounds like it should be sufficient for your task.

However, it sounds like you're using the double return value of Math.random() to choose between a fixed number of choices, which may further degrade the quality of the randomness. It would be better to use java.util.Random.nextInt() - just be sure to reuse the same Random object.

Sometimes, it doesn't appear so random by looking at a snapshot on a resource pool to see which pieces it's getting at that instant

Our brains are really good at spotting patterns in perfect randomness, so that means almost nothing.



回答2:

Math.Random's algorithm is "random enough" for any platform. The mathematical model used for creating psuedo-random numbers is a good one. It depends on how many threads you use. For anything but a really large number of threads, this will not give you even distribution (the nature of random numbers), and then Math.random() will give you plenty of overhead.

Try a better option: make a resource pool class, which distributes them evenly - and then just keep it's critical section in the "distribute" method protected.



回答3:

This thread can be usefull: How good is java.util.Random?

another alternatives:

  • generate a Random seed when init the random instance
  • if you using linux use /dev/urandom


回答4:

Per the javadoc Math.random() is just an easy way of using java.util.Random. That said it's just a pseudo random algorythm. An easy way of checking how random an algorythm realy is, is by drawing random points on x/y grid. You should not find any patterns.

To get real ramdom numbers you can use services like http://www.random.org . If this is to slow, maybe call it regularly to seed java.util.Random could get you closer to true random.



标签: java random