Skip to content

Comment on 0x5f3759df and the fast inverse square root (2012)parent

Comments

AFAICT transmute would work: http://rustbyexample.com/staging/unsafe.html

That's what's great about Rust, you can write unsafe code when you need it and it's isolated in `unsafe` blocks for easy auditing.

EDIT: Didn't test it too much, but looks like it works.

    fn fast_inv_sqrt(x: f32) -> f32 {
        let f: f32 = unsafe {
            let i: i32 = std::mem::transmute(x);
            std::mem::transmute(0x5f3759df - (i >> 1))
        };
        f * (1.5 - 0.5 * x * f * f)
    }

    println!("{}", fast_inv_sqrt(1.0));
      //=> 0.998307
    println!("{}", fast_inv_sqrt(255.0));
      //=> 0.062517
EDIT2: Shorter, more readable version.
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.