计算余弦算法

Rei*_*ein 0 c algorithm trigonometry

我创建了这个函数CalculateCos:

int Factorial (long int n)
{
    long int r = 1;
    for (int i = 2; i<=n; i++)
    {
        r = r*i;    
    }   

    return r;
}

float CalculateVariable(int CVnumber, int CVloopCounter)
{
    float CVresult = 0;
    CVresult = pow(CVnumber, (CVloopCounter*2)) / (long int)Factorial(CVnumber*2);

    return CVresult;
}

float CalculateCos(int number)
{
    float result = 1;
    int loopCounter = 1;
    int minusOrPlus = 1;
    while(loopCounter <= precision && loopCounter <= 8)
    {
        if(!minusOrPlus)
        {
            result = result - CalculateVariable(number, loopCounter);
            printf("%f\n", result);
            minusOrPlus = 1;
        }
        else
        {
            result = result + CalculateVariable(number, loopCounter);
            printf("%f\n", result);
            minusOrPlus = 0;
        }
        loopCounter++;
      }
      return result;
}
Run Code Online (Sandbox Code Playgroud)

之所以我在减法或添加后printf,是因为它给了我奇怪的输出,如:

Enter a number, for the cos function
6
1.000000
0.999997
1.000095
0.996588
1.122822
-3.421593
160.177368
-5729.385254
Result is: -5729.3852539
Official function result is:  0.9601703
Run Code Online (Sandbox Code Playgroud)

你能帮助我得到正确的结果吗?

更新:

现在我的解决方案是:

float CalculateCos(float number)
{
    float result = 0;
    float step = 1;
    int loopCounter = 1;

    while(loopCounter <= 5)
    {
        step = step * (-number) * number / (((2*loopCounter)-1)*((2*loopCounter)-2));
        result += step;
        loopCounter++;
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

pad*_*pad 7

目前的问题:

因为你的Factorial函数返回int并且你把它强制转换,所以long int即使16在你的情况输入之前它的结果也会溢出(14!> max_int).

你正在cos使用泰勒系列计算:

COS(X)= 1 - X 2 /2!+ X 4 /4!- X 6 /6!+ ...

我不会写代码.但是你的程序有些问题,可以轻松修复:

  1. 输入是弧度的,所以number应该是a float.
  2. 使用取幂和阶乘分别计算泰勒级数的每一步都会很快导致溢出.正确的方法是维护float变量:step = 1首先和 k 循环迭代step = step * (- x) * x / ((2*k-1)*(2*k)).通过这种方式,您只需添加stepresult中环,不需要minusOrPlus了.
  3. 循环迭代次数受限于8太小,因此结果可能不够精确.
  4. 我没有看到你precision在任何地方使用变量.它可用于检查结果的精度.例如,当abs(step) < precision我们要终止循环时.