added sampling

This commit is contained in:
Jean-Philippe Bossuat
2025-01-05 14:04:10 +01:00
parent 78cc0514ec
commit 4b8427c6b3
17 changed files with 181 additions and 32 deletions

8
sampling/Cargo.toml Normal file
View File

@@ -0,0 +1,8 @@
[package]
name = "sampling"
version = "0.1.0"
edition = "2021"
[dependencies]
rand_chacha = "0.3.1"
rand_core = "0.6.4"

1
sampling/src/lib.rs Normal file
View File

@@ -0,0 +1 @@
pub mod source;

45
sampling/src/source.rs Normal file
View File

@@ -0,0 +1,45 @@
use rand_chacha::rand_core::SeedableRng;
use rand_core::RngCore;
use rand_chacha::{ChaCha8Rng};
const MAXF64: f64 = 9007199254740992.0;
pub struct Source{
source:ChaCha8Rng,
}
impl Source{
pub fn new(seed: [u8;32]) -> Source{
Source{source:ChaCha8Rng::from_seed(seed)}
}
pub fn new_seed(&mut self) -> [u8;32]{
let mut seed: [u8; 32] = [0u8;32];
self.source.fill_bytes(&mut seed);
seed
}
#[inline(always)]
pub fn next_u64(&mut self) -> u64{
self.source.next_u64()
}
#[inline(always)]
pub fn next_u64n(&mut self, max: u64, mask: u64) -> u64{
let mut x: u64 = self.next_u64() & mask;
while x >= max{
x = self.next_u64() & mask;
}
x
}
#[inline(always)]
pub fn next_f64(&mut self, min: f64, max: f64) -> f64{
min + ((self.next_u64()<<11>>11) as f64)/MAXF64 * (max-min)
}
#[inline(always)]
pub fn fill_bytes(&mut self, bytes: &mut [u8]){
self.source.fill_bytes(bytes)
}
}