Last active
October 5, 2016 05:41
-
-
Save yurivish/bf683318d1fc905172e190ad61fc6c76 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based on a C implementation written by David Blackman and Sebastiano | |
// Vigna ([email protected]): http://xoroshiro.di.unimi.it/xoroshiro128plus.c | |
// Translated to Rust by Yuri Vishnevsky. Code kept close to the original. | |
/* This is the successor to xorshift128+. It is the fastest full-period | |
generator passing BigCrush without systematic failures, but due to the | |
relatively short period it is acceptable only for applications with a | |
mild amount of parallelism; otherwise, use a xorshift1024* generator. | |
Beside passing BigCrush, this generator passes the PractRand test suite | |
up to (and included) 16TB, with the exception of binary rank tests, | |
which fail due to the lowest bit being an LFSR; all other bits pass all | |
tests. We suggest to use a sign test to extract a random Boolean value. | |
Note that the generator uses a simulated rotate operation, which most C | |
compilers will turn into a single instruction. In Java, you can use | |
Long.rotateLeft(). In languages that do not make low-level rotation | |
instructions accessible xorshift128+ could be faster. | |
The state must be seeded so that it is not everywhere zero. If you have | |
a 64-bit seed, we suggest to seed a splitmix64 generator and use its | |
output to fill s. */ | |
// Notes: | |
// - The Rust nursery wants to add an implementation: | |
// https://github.com/rust-lang-nursery/rand/commit/e161873c10b84369451b4af0b42282436ccaa31b | |
// - The comment below mentions a relatively short period; it is 2^128 - 1. | |
pub struct Xoroshiro128PlusRng { | |
state: [u64; 2] | |
} | |
impl Xoroshiro128PlusRng { | |
pub fn new(s0: u64, s1: u64) -> Xoroshiro128PlusRng { | |
Xoroshiro128PlusRng { state: [s0, s1] } | |
} | |
#[inline(always)] | |
pub fn next(&mut self) -> u64 { | |
let s0 = self.state[0]; | |
let s1 = self.state[1]; | |
let result = s0.wrapping_add(s1); | |
let s1 = s1 ^ s0; | |
self.state[0] = s0.rotate_left(55) ^ s1 ^ (s1 << 14); // a, b | |
self.state[1] = s1.rotate_left(36); // c | |
result | |
} | |
pub fn jump(&mut self) { | |
const JUMP: [u64; 2] = [0xbeac0467eba5facb, 0xd86b048b86aa9922]; | |
let mut s0 = 0; | |
let mut s1 = 0; | |
for j in JUMP.iter() { | |
for b in 0..64 { | |
if j & (1u64 << b) != 0 { | |
s0 ^= self.state[0]; | |
s1 ^= self.state[1]; | |
} | |
self.next(); | |
} | |
} | |
self.state[0] = s0; | |
self.state[1] = s1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment