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

Morikawa Joe commented on MATH-1322:
------------------------------------

My patch is for setSeed(int seed), there is no problem in setSeed(long seed).
Actually, I compared apache MersenneTwiter with C++ mt19937 which is included 
in random.
And apache MersenneTwister generated different random value from C++ mt19937 
only if seed is negative.

The reason for the difference is that longMT is 0xffffffffffffffff.

{code:title=MersenneTwister.java|borderStyle=solid}
    public void setSeed(int seed) {
        // we use a long masked by 0xffffffffL as a poor man unsigned int
        long longMT = seed;

// longMT is 0xffffffffffffffff, but it is 0x00000000ffffffff in C++ or other 
language implementation.

        // NB: unlike original C code, we are working with java longs, the cast 
below makes masking unnecessary
        mt[0]= (int) longMT;
        for (mti = 1; mti < N; ++mti) {
            // See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier.
            // initializer from the 2002-01-09 C version by Makoto Matsumoto
            longMT = (1812433253l * (longMT ^ (longMT >> 30)) + mti) & 
0xffffffffL;
            mt[mti]= (int) longMT;
        }

        clear(); // Clear normal deviate cache
    }
{code}




Followings are the samples.

{code:title=Sample.java|borderStyle=solid}
MersenneTwister rng = new MersenneTwister();
rng.setSeed((int) -1);
// Without patch, "-931718226" is output.
// After applying patch, "419326371" is output.
System.out.println(rng.nextInt());
{code}


{code:title=CppSample.cpp|borderStyle=solid}
#include <iostream>
#include <random>

int main()
{
  std::mt19937 mt(0xFFFFFFFF);
  // 419326371 is displayed
  std::cout << mt() << std::endl;

  std::mt19937 mt1(-1);
  // 419326371 is displayed
  std::cout << mt() << std::endl;
}
{code}


> Negative integer seed for MersenneTwister is not working.
> ---------------------------------------------------------
>
>                 Key: MATH-1322
>                 URL: https://issues.apache.org/jira/browse/MATH-1322
>             Project: Commons Math
>          Issue Type: Bug
>    Affects Versions: 3.6
>            Reporter: Morikawa Joe
>              Labels: patch
>         Attachments: MersenneTwister.patch
>
>
> MersenneTwister.setSeed(int seed) has a bug.
> If seed is negative, longMT also becomes negative.
> First 32 bits are filled by 0xFFFFFFFF.
> But it should be positive. First 32 bits should be filled by 0x00000000.
> Ex) Integer -1 is 0xffffffff. 
> Long -1 is 0xffffffffffffffff.
> Long 0xffffffff is 4294967295.
> I created simple patch. 



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

Reply via email to