1

In Java there is a function Math.random() as well as a class Random. Why there are two entities for the seemingly same operation(ie Random number generation) and which one should be used when?

Geek
  • 26,489
  • 43
  • 149
  • 227
  • 1
    Possible double-post of, there ism ore than just the seed: http://stackoverflow.com/questions/738629/math-random-versus-random-nextintint – D.R. Mar 13 '13 at 14:12
  • 1
    Not a duplicate, the other question is explicitely about sampling integers via `Math.random()*n`. – kutschkem Mar 13 '13 at 14:23

2 Answers2

7

If you need to set an explicit random seed (yes you do that sometimes, when you want reproducible random numbers), then you use Random.

Apart from that, the random() method is just a shortcut to a fixed Random object, so you use that for brevity and when you don't care about the random seed (which is most of the time, i guess).

kutschkem
  • 7,826
  • 3
  • 21
  • 56
2

The 'difference' is that java.util.Random has methods to return more than one type of number. No casting needed. One constructor lets the user seed the generator for repeating sequences.

java.lang.Math.random() uses java.util.Random. It provides only doubles and has no seeding capability.

igarcia
  • 691
  • 1
  • 9
  • 26