2

I know how to use Math.random() in my code, but my question is specifically how does the function actually work? How does it pick a random number and is it possible to create your own randomizing function in java?

MooseMan55
  • 524
  • 2
  • 6
  • 21
  • Take a look at http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Random.java and decide for yourself. – hotzst Jan 25 '16 at 21:27
  • Any one who considers arithmetical methods of producing random digits is, of course, in a state of sin - John von Neumann – Steve Kuo Jan 25 '16 at 21:28
  • I know it's not really random, but it's close enough. – MooseMan55 Jan 25 '16 at 21:29
  • There is no such thing as random in computerland. In some cases you can have a "random generator" based on variables from the user like time you wait for something to happen. What usually happens is an algorithm creates a bunch of numbers by displacing a binary stream. something like a cyclic redundancy check used for error detection – Didier Lauwerys Jan 25 '16 at 21:34
  • I know people have said that a million times. But if you use a random function in any language, what you end up with is pretty friggin random. I don't know why it has to be mathematically classified as "true". – durbnpoisn Jan 25 '16 at 21:37
  • I think the distinction needed here is between random and pseudo-random sequences. A random sequence means the next number in the sequence is unpredictable despite complete knowledge of the method of determining each number in the sequence and previous numbers in the sequence. Pseudo-random sequences fail this test. They do, however, have several properties of random number sequences such as uniformity, independence, and others. – Χpẘ Jan 26 '16 at 06:08

2 Answers2

3

The Javadocs describe which algorithm is used:

You can write your own random number generator, but you won't be able to use it through Math.random() -- you'd just have to create your own method.

You may also find this previous StackOverflow question useful: Math.random() explained

Community
  • 1
  • 1
1

It works by using a single static instance of Random, and calling nextDouble() on it. Javadoc of Math.random() even says so.

Yes, you can always create you own class/method to generate random numbers using whichever algorithm you prefer.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • So how does nextDouble() return a random int then? – MooseMan55 Jan 25 '16 at 21:28
  • @MooseMan55 Read the javadoc of `Random` (click link above). First paragraph lists the source of the algorithm. Javadoc of `nextDouble()` actually shows the algorithm. In short, **read the javadoc**. – Andreas Jan 25 '16 at 21:30
  • @MooseMan55 the random int is used to create a `double` not the other way around. – Peter Lawrey Jan 25 '16 at 21:31