Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #34920
| From | Arne Vajhøj <arne@vajhoej.dk> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Re: Will Math.random return 0.0? |
| Date | 2016-07-16 14:37 -0400 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <nmdusk$1bu7$1@gioia.aioe.org> (permalink) |
| References | <rand-20160716162126@ram.dialup.fu-berlin.de> |
On 7/16/2016 11:24 AM, Stefan Ram wrote:
> I wrote the following program.
>
> public final class Main
> { public static void main( final java.lang.String[] args )
> { while( java.lang.Math.random() != 0.0 );
> java.lang.System.out.println( "0.0" ); }}
>
> What do you expect it's (average) runtime to be
> on average hardware?
>
> Can we be sure that it will ever terminate?
>
> (When the documentation says that »random« might
> return 0.0, this actually does not say that it
> ever will do so.)
The seed algorithm is:
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
and given that:
mod(0x5DEECE66D,4) is 1
0xB is odd
& ((1L << 48) - 1) must be equivalent to mod pow(2,48)
then the algorithm should have full cycle aka seed
will have all values including zero.
so if nextDouble() just returned seed/pow(2,48) then
it will return 0.0 occasionally.
But it does not. Instead it uses:
return (((long)next(26) << 27) + next(27)) / (double)(1L << 53);
So it will only return 0.0 if the high 26 bits of seed
and after update the high 27 bits of seed are both zero.
Now my math skills are not good enough to evaluate
whether that is indeed the case or not.
The above has pow(2,53) potential values but given the
seed cycle of pow(2,48) and the need for 2 calls, then
it will only be able to return pow(2,47) different values.
So odds is only 1:64 for returning zero for the math challenged
like me.
But you could test it by iterating pow(2,47) times. Which should
be computable.
Alternative wait for somebody with better math skills to solve
it analytical.
BTW, I think the question is rather pointless. If the difference
between 0.0 and almost 0.0 matters then double is not the right
data type in the first place.
Arne
Back to comp.lang.java.programmer | Previous | Next — Next in thread | Find similar | Unroll thread
Re: Will Math.random return 0.0? Arne Vajhøj <arne@vajhoej.dk> - 2016-07-16 14:37 -0400 Re: Will Math.random return 0.0? Arne Vajhøj <arne@vajhoej.dk> - 2016-07-16 16:51 -0400
csiph-web