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 java.util.Arrays; 21 import org.apache.commons.rng.core.util.NumberFactory; 22 23 /** 24 * A fast RNG. 25 * 26 * @see <a href="http://xorshift.di.unimi.it/xorshift1024star.c"> 27 * Original source code</a> 28 * 29 * @see <a href="https://en.wikipedia.org/wiki/Xorshift">Xorshift (Wikipedia)</a> 30 * @since 1.0 31 */ 32 public class XorShift1024Star extends LongProvider { 33 /** Size of the state vector. */ 34 private static final int SEED_SIZE = 16; 35 /** State. */ 36 private final long[] state = new long[SEED_SIZE]; 37 /** Index in "state" array. */ 38 private int index; 39 40 /** 41 * Creates a new instance. 42 * 43 * @param seed Initial seed. 44 * If the length is larger than 16, only the first 16 elements will 45 * be used; if smaller, the remaining elements will be automatically 46 * set. 47 */ 48 public XorShift1024Star(long[] seed) { 49 setSeedInternal(seed); 50 } 51 52 /** {@inheritDoc} */ 53 @Override 54 protected byte[] getStateInternal() { 55 final long[] s = Arrays.copyOf(state, SEED_SIZE + 1); 56 s[SEED_SIZE] = index; 57 58 return NumberFactory.makeByteArray(s); 59 } 60 61 /** {@inheritDoc} */ 62 @Override 63 protected void setStateInternal(byte[] s) { 64 checkStateSize(s, (SEED_SIZE + 1) * 8); 65 66 final long[] tmp = NumberFactory.makeLongArray(s); 67 68 System.arraycopy(tmp, 0, state, 0, SEED_SIZE); 69 index = (int) tmp[SEED_SIZE]; 70 } 71 72 /** 73 * Seeds the RNG. 74 * 75 * @param seed Seed. 76 */ 77 private void setSeedInternal(long[] seed) { 78 // Reset the whole state of this RNG (i.e. "state" and "index"). 79 // Filling procedure is not part of the reference code. 80 fillState(state, seed); 81 index = 0; 82 } 83 84 /** {@inheritDoc} */ 85 @Override 86 public long next() { 87 final long s0 = state[index]; 88 long s1 = state[index = (index + 1) & 15]; 89 s1 ^= s1 << 31; // a 90 state[index] = s1 ^ s0 ^ (s1 >>> 11) ^ (s0 >>> 30); // b,c 91 return state[index] * 1181783497276652981L; 92 } 93 }