3次テイラー級数のサンプルコード

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

/* F(x,y) */
double F(double x, double y){
    return x * y; /* F(x,y) = xy */
}

/* Fx(x,y) */
double Fx(double x, double y){
    return y + x * F(x,y);
}

/* Fxx(x,y) */
double Fxx(double x, double y){
    return 2 * F(x,y) + x * Fx(x,y);
}

double taylor(int n, double x0, double y0, double xn){
    int i;
    double x,y,h;
    x = x0; y = y0; /* initial value */
    h = (xn - x0) /n;
    for (i = 0; i < n; i++)
    {
        y += h * (F(x,y) + (h/2) * (Fx(x,y)  + (h/3) * Fxx(x,y)));
        x = x0 + i * h;
    }
        return y;
}

int main(void)
{
    int n = 100;
    printf("解析値\n");
    printf("%f\n",taylor(n,0,1,1));

    printf("理論値\n");
    printf("%f\n", exp(0.5));
    return 0;
}

出力結果

数値解析
1.632479
理論値
1.648721