Hacker News new | past | comments | ask | show | jobs | submit login

Tl;DR :

The fast inverse square root is based on the fact that the integer representation of a floating point number is a rough approximation of its logarithm.

So convert floating point to its integer representation. So now you have its approximate logarithm. Now take half of that and improve that with some Newton raphson.




So convert floating point to its integer representation.

Would something dirty like this be feasible in rust?


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.


It would be exact if we used a logarithm based number system: http://en.wikipedia.org/wiki/Logarithmic_number_system

This kind of system is beautiful, but there is no easy way to add and subtract.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: