计算具有sin / cos LUT的tan

时间:2012-12-07 14:51:18

标签: c optimization

#define PARTPERDEGREE 1
double mysinlut[PARTPERDEGREE * 90 + 1];
double mycoslut[PARTPERDEGREE * 90 + 1];
void MySinCosCreate()
{
    int i;
    double angle, angleinc;

    // Each degree also divided into 10 parts
    angleinc = (M_PI / 180) / PARTPERDEGREE;
    for (i = 0, angle = 0.0; i <= (PARTPERDEGREE * 90 + 1); ++i, angle += angleinc)
    {
        mysinlut[i] = sin(angle);
    }

    angleinc = (M_PI / 180) / PARTPERDEGREE;
    for (i = 0, angle = 0.0; i <= (PARTPERDEGREE * 90 + 1); ++i, angle += angleinc)
    {
        mycoslut[i] = cos(angle);
    }
}


double MySin(double rad)
{
    int ix;
    int sign = 1;
    double angleinc = (M_PI / 180) / PARTPERDEGREE;

    if(rad > (M_PI / 2))
        rad = M_PI / 2 - (rad - M_PI / 2);

    if(rad < -(M_PI / 2))
        rad = -M_PI / 2 - (rad + M_PI / 2);

    if(rad < 0)
    {
        sign = -1;
        rad *= -1;
    }

    ix = (rad * 180) / M_PI * PARTPERDEGREE;
    double h = rad - ix*angleinc;
    return sign*(mysinlut[ix] + h*mycoslut[ix]);
}

double MyCos(double rad)
{
    int ix;
    int sign = 1;
    double angleinc = (M_PI / 180) / PARTPERDEGREE;


    if(rad > M_PI / 2)
    {
        rad = M_PI / 2 - (rad - M_PI / 2);
        sign = -1;
    }
    else if(rad < -(M_PI / 2))
    {
        rad = M_PI / 2 + (rad + M_PI / 2);
        sign = -1;
    }
    else if(rad > -M_PI / 2 && rad < M_PI / 2)
    {   
        rad = abs(rad);
        sign = 1;
    }

    ix = (rad * 180) / M_PI * PARTPERDEGREE;

    double h = rad - ix*angleinc;
    return sign*(mycoslut[ix] - h*mysinlut[ix]);
}

double MyTan(double rad)
{
    return MySin(rad) / MyCos(rad);
}

事实证明,使用除法计算tan比原始tan函数更昂贵。

有没有办法在没有除法运算的情况下使用sin / cos查找表值来计算tan,因为在我的MCU上划分是很昂贵的。

使用{/ 1}} LUT并使用tan / sin或tan / cos提取结果是否更好,因为它现在为sin / cos完成了?

1 个答案:

答案 0 :(得分:0)

特别是在微控制器中,通常可以通过log&amp; amp;来优化除法y / x。 exp表,或迭代乘法,直到分母1 + - eps = 1 + - x ^(2 ^ n)为零。

y/X = y / (1-x) 
    = (1+x)y / (1+x)(1-x)
    = (1+x)(1+x^2)y / (1-x^2)(1+x^2)
    = (1+x)(1+x^2)(1+x^4)y / (1-x^4)(1+x^4)