View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.rng.core.source64;
19  
20  import org.apache.commons.rng.core.util.NumberFactory;
21  
22  /**
23   * A fast RNG, with 64 bits of state, that can be used to initialize the
24   * state of other generators.
25   *
26   * @see <a href="http://xorshift.di.unimi.it/splitmix64.c">
27   * Original source code</a>
28   *
29   * @since 1.0
30   */
31  public class SplitMix64 extends LongProvider {
32      /** State. */
33      private long state;
34  
35      /**
36       * Creates a new instance.
37       *
38       * @param seed Initial seed.
39       * @since 1.3
40       */
41      public SplitMix64(long seed) {
42          state = seed;
43      }
44  
45      /**
46       * Creates a new instance.
47       *
48       * @param seed Initial seed.
49       */
50      public SplitMix64(Long seed) {
51          // Support for Long to allow instantiation through the
52          // rng.simple.RandomSource factory methods.
53          setSeedInternal(seed);
54      }
55  
56      /**
57       * Seeds the RNG.
58       *
59       * @param seed Seed.
60       */
61      private void setSeedInternal(Long seed) {
62          state = seed.longValue();
63      }
64  
65      /** {@inheritDoc} */
66      @Override
67      public long next() {
68          long z = state += 0x9e3779b97f4a7c15L;
69          z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
70          z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
71          return z ^ (z >>> 31);
72      }
73  
74      /** {@inheritDoc} */
75      @Override
76      protected byte[] getStateInternal() {
77          return composeStateInternal(NumberFactory.makeByteArray(state),
78                                      super.getStateInternal());
79      }
80  
81      /** {@inheritDoc} */
82      @Override
83      protected void setStateInternal(byte[] s) {
84          final byte[][] c = splitStateInternal(s, 8);
85  
86          state = NumberFactory.makeLong(c[0]);
87          super.setStateInternal(c[1]);
88      }
89  }