首页 > 解决方案 > C 中的泰勒级数 - math.h 与自己的实现

问题描述

虽然我在这里找到了一些有关泰勒级数的帖子,但我想寻求支持:我编写了sin(x)基于泰勒方程的 C 代码进行计算。作为参数,我的函数采用 rad 值和泰勒级数的预期长度。

我观察到的是,我的函数返回与正弦相同的值,math.h直到x <= 1.8-> 所有高于此值的返回值都不同。这是代码:

这是在线调试器中的代码(这是我第一次粘贴,所以它可能无法正常工作) https://onlinegdb.com/f4ymuMloW

整个代码:

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

int factorial(int x) {
    if (x == 0 || x == 1) 
        return 1;

    return x * factorial(x-1);
}

/*
    sin(x) = sum[k=0, n] ((-1^k) * x^(2k+1))/(2k+1)!        
 */

double taylorSine(double x, int k) {
    double ret = 0.0f;
    for (int i = 0 ; i < k; i++) {
        double l = pow(-1, i) * pow(x, 2 * i + 1);
        long long unsigned int m = factorial(2 * i + 1);
        ret += l/(double)m;
    }
    return ret;
}

int main(int argc, char **argv) {
    float low,up;
    /* default */
    int sumsteps = 5;
    double res = 0.01f;

    if (argc == 1) {
        low = -3.14f;
        up = 3.14f;            
    } 
    else if (argc == 3) {
        low = atof(argv[1]);
        sumsteps = atoi(argv[2]);
    } 
    else {
        printf("wrong number of args\n");
        return 0;
    }

    double r = taylorSine(low, sumsteps);
    printf("%f,%f\n", low, r);
    printf("sin(x)=%f\n", sin(low));        

    return 0;
}

和输出:

Starting program: /home/a.out 0 7
0.000000,0.000000
sin(x)=0.000000
[Inferior 1 (process 2146) exited normally]
(gdb) run 1.57 7
Starting program: /home/a.out 1.57 7
1.570000,1.000000
sin(x)=1.000000
[Inferior 1 (process 2147) exited normally]
(gdb) run 3.14 7
Starting program: /home/a.out 3.14 7
3.140000,0.002643
sin(x)=0.001593
[Inferior 1 (process 2148) exited normally]
(gdb) run 6.28 7
Starting program: /home/a.out 6.28 7
6.280000,9.053029
sin(x)=-0.003185
[Inferior 1 (process 2149) exited normally]
(gdb) 

标签: ctaylor-series

解决方案


您的阶乘函数将溢出 (2*7+1)!== 1,307,674,368,000,请尝试使用双版本。

double factorial(double x)
{
  double sum = 1.0;
  for (double y = 2.0; y < x; y += 1.0 )
  {
    sum*=y;
  }
  return sum;
}

推荐阅读