Is it possible to write Quake's fast InvSqrt() function in Rust?

前端 未结 3 1392
太阳男子
太阳男子 2021-01-29 23:03

This is just to satisfy my own curiosity.

Is there an implementation of this:

float InvSqrt (float x)
{
   float xh         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 00:04

    You may use std::mem::transmute to make needed conversion:

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

    You can look for a live example here: here

提交回复
热议问题