Skip to content

Instantly share code, notes, and snippets.

@warrenrentlytics
Created October 10, 2018 05:34
Show Gist options
  • Save warrenrentlytics/9c9dde9276e7808a1db7c3d35ed3bc86 to your computer and use it in GitHub Desktop.
Save warrenrentlytics/9c9dde9276e7808a1db7c3d35ed3bc86 to your computer and use it in GitHub Desktop.
Working PCG32 generator, updated from https://github.com/EricIO/pcg-rust
// Copyright 2015 Eric Skoglund
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Updates by Warren Henning, 2018
pub struct Pcg32Random {
pub state: u64,
pub inc: u64,
}
pub fn pcg32_random_r(rng: &mut Pcg32Random) -> u32 {
let oldstate = rng.state;
rng.state = oldstate.wrapping_mul(6364136223846793005u64).wrapping_add(rng.inc);
let xorshifted = (((oldstate >> 18) ^ oldstate) >> 27) as u32;
let rot = oldstate >> 59;
let srot = -(rot as i64);
return (xorshifted >> rot) | (xorshifted << (srot & 31));
}
pub fn pcg32_srandom_r(rng : &mut Pcg32Random, initstate : u64, initseq : u64) {
rng.state = 0u64;
rng.inc = (initseq << 1u64) | 1u64;
pcg32_random_r(rng);
rng.state += initstate;
pcg32_random_r(rng);
}
pub fn pcg32_boundedrand_r(rng: &mut Pcg32Random, bound : u32) -> u32 {
let sbound = bound as i32;
let threshold = (-sbound % sbound) as u32;
loop {
let r = pcg32_random_r(rng);
if r >= threshold {
return r % bound;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment