[ 
https://issues.apache.org/jira/browse/MATH-1300?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=15065695#comment-15065695
 ] 

Thomas Neidhart commented on MATH-1300:
---------------------------------------

The Random class does not guarantee that for any chunk size the same sequence 
is generated. In fact it always gets the next 32 bits and uses as much as 
needed.

This means that for chunk sizes that are not multiples of 4, the test from 
Gilles will also fail.

I do see a problem in the nextBytes implementation in BitStreamGenerator, as 
there are unnecessary calls to next(int) in case the chunk size is a multiple 
of 4. I think the proposed patches could be further improved into something 
like that:

{code}
    public void nextBytes(byte[] bytes) {
        final int len = bytes.length;
        for (int i = 0; i < len;) {
            int random = nextInt();
            int n = Math.min(len - i, 4);
            while (n-- > 0) {
                bytes[i++] = (byte) random;
                random >>= 8;
            }
        }
    }
{code}

> BitsStreamGenerator#nextBytes(byte[]) is wrong
> ----------------------------------------------
>
>                 Key: MATH-1300
>                 URL: https://issues.apache.org/jira/browse/MATH-1300
>             Project: Commons Math
>          Issue Type: Bug
>    Affects Versions: 3.5
>            Reporter: Rostislav Krasny
>         Attachments: MersenneTwister2.java, TestMersenneTwister.java
>
>
> Sequential calls to the BitsStreamGenerator#nextBytes(byte[]) must generate 
> the same sequence of bytes, no matter by chunks of which size it was divided. 
> This is also how java.util.Random#nextBytes(byte[]) works.
> When nextBytes(byte[]) is called with a bytes array of length multiple of 4 
> it makes one unneeded call to next(int) method. This is wrong and produces an 
> inconsistent behavior of classes like MersenneTwister.
> I made a new implementation of the BitsStreamGenerator#nextBytes(byte[]) see 
> attached code.



--
This message was sent by Atlassian JIRA
(v6.3.4#6332)

Reply via email to