SplitMix64.java

  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. package org.apache.commons.rng.core.source64;

  18. import org.apache.commons.rng.core.util.NumberFactory;

  19. /**
  20.  * A fast RNG, with 64 bits of state, that can be used to initialize the
  21.  * state of other generators.
  22.  *
  23.  * @see <a href="http://xorshift.di.unimi.it/splitmix64.c">
  24.  * Original source code</a>
  25.  *
  26.  * @since 1.0
  27.  */
  28. public class SplitMix64 extends LongProvider {
  29.     /** State. */
  30.     private long state;

  31.     /**
  32.      * Creates a new instance.
  33.      *
  34.      * @param seed Initial seed.
  35.      * @since 1.3
  36.      */
  37.     public SplitMix64(long seed) {
  38.         state = seed;
  39.     }

  40.     /**
  41.      * Creates a new instance.
  42.      *
  43.      * @param seed Initial seed.
  44.      */
  45.     public SplitMix64(Long seed) {
  46.         // Support for Long to allow instantiation through the
  47.         // rng.simple.RandomSource factory methods.
  48.         state = seed.longValue();
  49.     }

  50.     /** {@inheritDoc} */
  51.     @Override
  52.     public long next() {
  53.         long z = state += 0x9e3779b97f4a7c15L;
  54.         z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
  55.         z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
  56.         return z ^ (z >>> 31);
  57.     }

  58.     /** {@inheritDoc} */
  59.     @Override
  60.     protected byte[] getStateInternal() {
  61.         return composeStateInternal(NumberFactory.makeByteArray(state),
  62.                                     super.getStateInternal());
  63.     }

  64.     /** {@inheritDoc} */
  65.     @Override
  66.     protected void setStateInternal(byte[] s) {
  67.         final byte[][] c = splitStateInternal(s, 8);

  68.         state = NumberFactory.makeLong(c[0]);
  69.         super.setStateInternal(c[1]);
  70.     }
  71. }