arc-graph-core 0.4.0

Framework-free knowledge-graph model for arc-graph: nodes, typed kinds, weighted edges, adjacency index, filter/search and JSON/CSV import.
Documentation
//! 确定性随机数(方案 §4:固定随机种子保证可复现)。
//!
//! 不引入 `rand` 依赖:SplitMix64 播种 + xorshift64* 输出,
//! 跨平台逐位一致(同种子 → 同序列 → 同布局)。

/// 种子化 RNG。只用于初始位置抖动等非物理量,避免平台相关的浮点差异。
#[derive(Clone, Debug)]
pub struct Rng {
    state: u64,
}

impl Rng {
    pub fn new(seed: u64) -> Self {
        // SplitMix64:把任意种子打散到完整 64 位状态。
        let mut s = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut out = 0u64;
        for _ in 0..4 {
            s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
            let mut z = s;
            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
            out = z ^ (z >> 31);
        }
        Self { state: out }
    }

    /// xorshift64* 下一个 64 位值。
    pub fn next_u64(&mut self) -> u64 {
        let mut x = self.state;
        x ^= x >> 12;
        x ^= x << 25;
        x ^= x >> 27;
        self.state = x;
        x.wrapping_mul(0x2545_F491_4F6C_DD1D)
    }

    /// [0, 1) 均匀 f32。
    pub fn next_f32(&mut self) -> f32 {
        ((self.next_u64() >> 40) as f32) / ((1u32 << 24) as f32)
    }

    /// [-r, r) 均匀 f32。
    pub fn next_symmetric(&mut self, r: f32) -> f32 {
        (self.next_f32() * 2.0 - 1.0) * r
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn same_seed_same_sequence() {
        let mut a = Rng::new(42);
        let mut b = Rng::new(42);
        for _ in 0..1000 {
            assert_eq!(a.next_u64(), b.next_u64());
        }
    }

    #[test]
    fn different_seed_diverges() {
        let mut a = Rng::new(1);
        let mut b = Rng::new(2);
        let sa: Vec<u64> = (0..16).map(|_| a.next_u64()).collect();
        let sb: Vec<u64> = (0..16).map(|_| b.next_u64()).collect();
        assert_ne!(sa, sb);
    }

    #[test]
    fn f32_in_range() {
        let mut r = Rng::new(7);
        for _ in 0..10_000 {
            let v = r.next_f32();
            assert!((0.0..1.0).contains(&v));
            let s = r.next_symmetric(3.0);
            assert!((-3.0..3.0).contains(&s));
        }
    }
}