为何卡马克开平方算法精确度这么低

为什么卡马克开平方算法精确度这么低?
本帖最后由 Razor87 于 2013-07-18 21:50:46 编辑
代码如下:
#include <iostream>
#include <math.h>
using namespace std;
float InvSqrt (float x)
{        
        float xhalf = 0.5f*x;
        int i = *(int*)&x;
        i = 0x5f3759df - (i >> 1); // 计算第一个近似根
        x = *(float*)&i;
        x = x*(1.5f - xhalf*x*x); // 牛顿迭代法
        return x;
}

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));
}

int main(){
        float a = 0.25;
        cout << InvSqrt(a) << endl;
        cout << CarmSqrt(a) << endl;
        cout << sqrt(a) << endl;
        return 0;
}


结果如下:
1.99661
0.488594
0.5
请按任意键继续. . .