使用泰勒展开式的正弦函数(C 编程)

Sha*_*ack 5 c trigonometry function

是问题..

这就是我到目前为止所做的

#include <stdio.h>
#include <math.h>

long int factorial(int m)
{
    if (m==0 || m==1) return (1);
    else      return (m*factorial(m-1));
}
double power(double x,int n)
{
    double val=1;
    int i;
    for (i=1;i<=n;i++)
    {
        val*=x;
    }
    return val;
}

double sine(double x)
{
    int n;
    double val=0;
    for (n=0;n<8;n++)
    {
        double p = power(-1,n);
        double px = power(x,2*n+1);
        long fac = factorial(2*n+1);
        val += p * px / fac;
    }
    return val;
}

int main()
{
    double x;
    printf("Enter angles in degrees: ");
    scanf("%lf",&x);
    printf("\nValue of sine of %.2f is %.2lf\n",x,sine(x * M_PI / 180));
    printf("\nValue of sine of %.2f from library function is %.2lf\n",x,sin(x * M_PI / 180));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是该程序在 0 到 180 度范围内工作得很好,但超出这个范围就会出错。此外,当我将 的值增加到n超过for (n=0;n<8;n++)8 时,我会出现严重错误。该算法没有任何问题,我'我在我的计算器中测试了它,程序似乎也很好..我认为问题是由于数据类型的范围造成的..我应该纠正什么来消除这个错误?
谢谢..

Fre*_*ung 2

15!确实超出了 32 位整数可以容纳的范围。如果我是你,我会一直使用双打。

对于较大的 x 值,泰勒级数sin(x)收敛得更慢。对于 x 在 -π,π 之外。我会加/减 2*π 的倍数以获得尽可能小的 x 。