what is internal logic behind math.random()?

## 5 Replies - 4285 Views - Last Post: 18 August 2010 - 04:59 PM

##
**Replies To:** MATH.RANDOM()

### #2

## Re: MATH.RANDOM()

Posted 14 August 2010 - 07:15 AM

### #3

## Re: MATH.RANDOM()

Posted 14 August 2010 - 07:57 AM

It takes a seed, based on the time of day, and applies a linear congruential formula on that seed to produce a random number. So it's actually not 100% random, but close as you can get.

This article talks about it more, even gives you the formula:

http://www.particle....vaRandNums.html

This article talks about it more, even gives you the formula:

http://www.particle....vaRandNums.html

### #4

## Re: MATH.RANDOM()

Posted 18 August 2010 - 01:20 AM

You should check the javadoc, they have provided the wonderfull detail on Math.random() method

### #5

## Re: MATH.RANDOM()

Posted 18 August 2010 - 03:50 PM

mk.ranjan, on 18 August 2010 - 02:20 AM, said:

You should check the javadoc, they have provided the wonderfull detail on Math.random() method

Not really. All it says is:

An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula.

*(See Donald Knuth, The Art of Computer Programming, Volume 3, Section 3.2.1.)*

### #6

## Re: MATH.RANDOM()

Posted 18 August 2010 - 04:59 PM

You must be looking at Random class, not Math.random(). As I saw this under Math.random().

Googled further and found this for nextDouble() from here.

Quote

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression

new java.util.Random

This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.

This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.

When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression

new java.util.Random

This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.

This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.

Googled further and found this for nextDouble() from here.

public double nextDouble() { return (((long)next(26) << 27) + next(27)) / (double)(1L << 53); }

Page 1 of 1