close

在C語言裡,一般的寫法都是用math library裡的sqrt ,不過在講究速度的CG運算中,有人用了種更高明(也就是更噁心的意思...XD)的寫法,是利用牛頓法再配合幾個magic number達成的。

以下是來自Quake III裡用來算平方根倒數的code:

float CarmSqrt(float x){
    union{
        int intPart;
        float floatPart;
    } convertor;
    union{
        int intPart;
        float floatPart;
    } convertor2;
    convertor.floatPart = x;
    convertor2.floatPart = x;
    convertor.intPart = 0x1FBCF800 + (convertor.intPart >> 1);
    convertor2.intPart = 0x5f3759df - (convertor2.intPart >> 1);
    return 0.5f*(convertor.floatPart + (x * convertor2.floatPart));
}


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 cym 的頭像
    cym

    cym's blog

    cym 發表在 痞客邦 留言(0) 人氣()