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 state = seed.longValue();
54 }
55
56 /** {@inheritDoc} */
57 @Override
58 public long next() {
59 long z = state += 0x9e3779b97f4a7c15L;
60 z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
61 z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
62 return z ^ (z >>> 31);
63 }
64
65 /** {@inheritDoc} */
66 @Override
67 protected byte[] getStateInternal() {
68 return composeStateInternal(NumberFactory.makeByteArray(state),
69 super.getStateInternal());
70 }
71
72 /** {@inheritDoc} */
73 @Override
74 protected void setStateInternal(byte[] s) {
75 final byte[][] c = splitStateInternal(s, 8);
76
77 state = NumberFactory.makeLong(c[0]);
78 super.setStateInternal(c[1]);
79 }
80 }