Re: [rng] nextInt(int) and nextLong(long) can be improved

2019-04-10 Thread Gilles Sadowski
Le mer. 10 avr. 2019 à 18:26, Alex Herbert a écrit : > > > On 10/04/2019 15:59, Gilles Sadowski wrote: > > Hello. > > > > Le mer. 10 avr. 2019 à 15:22, Alex Herbert a > > écrit : > >> On 10/04/2019 13:46, Alex Herbert wrote: > >>> The code for nextInt(int) checks the range number n is a power

Re: [rng] nextInt(int) and nextLong(long) can be improved

2019-04-10 Thread Alex Herbert
On 10/04/2019 15:59, Gilles Sadowski wrote: Hello. Le mer. 10 avr. 2019 à 15:22, Alex Herbert a écrit : On 10/04/2019 13:46, Alex Herbert wrote: The code for nextInt(int) checks the range number n is a power of two and if so it computes a fast solution: return (int) ((n * (long)

Re: [rng] nextInt(int) and nextLong(long) can be improved

2019-04-10 Thread Gilles Sadowski
Hello. Le mer. 10 avr. 2019 à 15:22, Alex Herbert a écrit : > > On 10/04/2019 13:46, Alex Herbert wrote: > > The code for nextInt(int) checks the range number n is a power of two > > and if so it computes a fast solution: > > > > return (int) ((n * (long) (nextInt() >>> 1)) >> 31); > > > >

Re: [rng] nextInt(int) and nextLong(long) can be improved

2019-04-10 Thread Alex Herbert
On 10/04/2019 13:46, Alex Herbert wrote: The code for nextInt(int) checks the range number n is a power of two and if so it computes a fast solution:     return (int) ((n * (long) (nextInt() >>> 1)) >> 31); This scales a 31 bit positive number by a power of 2 (i.e. n) then discards bits. So

[rng] nextInt(int) and nextLong(long) can be improved

2019-04-10 Thread Alex Herbert
The code for nextInt(int) checks the range number n is a power of two and if so it computes a fast solution:     return (int) ((n * (long) (nextInt() >>> 1)) >> 31); This scales a 31 bit positive number by a power of 2 (i.e. n) then discards bits. So this is effectively just a left shift