commons-issues mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Rostislav Krasny (JIRA)" <>
Subject [jira] [Commented] (MATH-1300) BitsStreamGenerator#nextBytes(byte[]) is wrong
Date Sat, 19 Dec 2015 19:00:47 GMT


Rostislav Krasny commented on MATH-1300:

According to the code comments both the CM and the Mantissa implementations of MersenneTwister
are based on the same code "developed by Makoto Matsumoto and Takuji Nishimura during 1996-1997".
The main difference between them is that Mantissa implementation extends the standard java.util.Random
and uses JDK's nextBytes() method while the CM implementation extends its own BitsStreamGenerator
with its own nextBytes() method implementation. So the reference behavior for the nextBytes()
method must be the java.util.Random since it is a part of the JDK and so it is the standard.

BTW I  looked at my code again and found that & 0xff operations are not needed. Narrowing
Primitive Conversion just discards all unneded bits above the byte, so we don't need to do
it by ourself before int to byte type casting.

So I propose this new code of the BitsStreamGenerator#nextBytes() method with even a little
bit better performance
	public void nextBytes(byte[] bytes) {
		int random;
		int index = 0;
		for (int max = bytes.length & 0x7ffffffc; index < max;) {
			random = next(32);
			bytes[index++] = (byte) random;
			bytes[index++] = (byte) (random >>> 8);
			bytes[index++] = (byte) (random >>> 16);
			bytes[index++] = (byte) (random >>> 24);

		if (index < bytes.length) {
			random = next(32);
			while (true) {
				bytes[index++] = (byte) random;
				if (index < bytes.length) {
					random >>>= 8;
				} else {

> BitsStreamGenerator#nextBytes(byte[]) is wrong
> ----------------------------------------------
>                 Key: MATH-1300
>                 URL:
>             Project: Commons Math
>          Issue Type: Bug
>    Affects Versions: 3.5
>            Reporter: Rostislav Krasny
>         Attachments:,
> 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[])
> 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

This message was sent by Atlassian JIRA

View raw message