Created
September 28, 2013 21:21
-
-
Save aperezdc/6746727 to your computer and use it in GitHub Desktop.
RAND31 random number generator in Rust. Suitable for generating white noise for audio applications.
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
/* | |
* rand31.rs | |
* Copyright (C) 2013 Adrian Perez <[email protected]> | |
* | |
* Implements the rand31 random number generation algorithm, which is | |
* particularly suitable for use as white noise for sound applications. | |
* | |
* For more information on the algorithm, please refer to: | |
* http://www.firstptr.com.au/dsp/rand31/ | |
* | |
* Distributed under terms of the MIT license. | |
*/ | |
static constapmc: u64 = 16807; | |
pub struct Rand31 { | |
priv seed: u64 | |
} | |
impl Rand31 { | |
pub fn next(&mut self) -> u64 { | |
let mut lo: u64 = constapmc * (self.seed & 0xFFFF); | |
let hi: u64 = constapmc * (self.seed >> 16); | |
lo += (hi & 0x7FFF) << 16; | |
lo += hi >> 15; | |
if lo > 0x7FFFFFFF { | |
lo -= 0x7FFFFFFF; | |
} | |
self.seed = lo; | |
self.seed | |
} | |
pub fn nextf(&mut self) -> f64 { | |
(self.next() as f64) / 2147483647.0 | |
} | |
} | |
pub fn new_with_seed(seed: u64) -> Rand31 { Rand31 { seed: seed } } | |
pub fn new() -> Rand31 { new_with_seed(1) } | |
// This main() functions is for testing. | |
fn main () { | |
let mut r = new(); | |
loop { | |
println(format!("{:u}", r.next())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment