Re: random real number between 0 (inclusive) and 1 (inclusive)
Dr J R Stockton wrote:
In comp.lang.java.programmer message <fgobj5$292n$1@ihnp4.ucsd.edu>,
Mon, 5 Nov 2007 16:13:23, Patricia Shanahan <pats@acm.org> posted:
Dr J R Stockton wrote:
In comp.lang.java.programmer message <jnasi31porsaqq0nb4u3r6mkdt3otanu9r
@4ax.com>, Sun, 4 Nov 2007 20:28:11, Roedy Green <see_website@mindprod.c
om.invalid> posted:
On Sun, 04 Nov 2007 19:35:39 -0000, "(-Peter-)"
<garfieldpbj@gmail.com> wrote, quoted or indirectly quoted someone who
said :
What I need is to generate a lot of random real numbers between 0 and
1, both inclusive (normally it's possible to generate the number
between 0(inclusive) and 1 (exclusive!!!) )
Multiply the number by 1+ulp where ulp in the smallest increment in a
double in the vicinity of 1.0
By stretching [0, 1) to cover [0, 1] there is necessarily a hole
created, perhaps at 0.5 .
By creating random R in [0, 1) and doing if (R==0.5) { R = 1 } ;
(apologies; I'm slowly learning to read Java;
writing it properly may follow)
one also gets a hole.
Now replace 0.5 by a random in [0, 1) independently generated and
renewed each time it is hit (so not correlated with the main Random),
and ISTM that all values in [0, 1] should be obtained with virtually
equal probability.
The Java code would be something like:
double nextInclusiveDouble(){
double r = nextDouble();
return r == nextDouble() ? 1 : r;
}
That's not the code for what I suggested. Whether it will do well
enough must depend on the details behind nextDouble. I suggested an
independent generator to maintain the Hole. Pseudo?-JavaSCRIPT :
var Hole = SomeOtherRandomFunction()
function nextInclusiveDouble() { var T
if ((T=Math.random())==Hole) {
T = 1 ; Hole = SomeOtherRandomFunction() }
return T }
Since SomeOtherRandomFunction is called only when Math.random() hits
Hole, it can be slow : something from Knuth implemented in Java[script].
Java has two built-in random number generators, java.util.Random and a
subclass, java.security.SecureRandom. SecureRandom is the class to use
if you want a different, possibly better, but slower generator.
Does anyone know whether nextDouble produces pairs of consecutive equal
numbers with the correct probability, remembering that it is based on a
pseudo-random number generator?
Is nextDouble based on *A* specific PRNG, or is it based on whichever
PRNG the system author happened to like? In the latter case, your
question may have multiple answers.
Random's nextDouble is specified to be based on this method:
synchronized protected int next(int bits) {
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
return (int)(seed >>> (48 - bits));
}
seed is a long.
Each call to nextDouble uses a next(26) and a next(27).
You can see a lot of this information in the Random API documentation at
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html
Patricia