2018年12月30日 星期日

C語言 例題3-1 計算微分近似解 (向前差 / 向後差 / 中央差)

C語言 例題3-1  計算微分近似解 (向前差 / 向後差 / 中央差)

以 f(x) = sin(x) ,取 h = 0.01,

以 C 語言計算在 x=1 之微分值為何,並與 cos(1) 做結果比較。





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

double func(double x) // 欲微分函數
{ return sin(x) ;}

double FordDiff(double x, double h, double (*fx)(double))
{ // 前差微分
    return ( fx(x+h) - fx(x) ) / h;
}

double BackDiff(double x, double h, double (*fx)(double))
{ // 後差微分
    return ( fx(x) - fx(x-h) ) / h;
}

double MidDiff(double x, double h,double (*fx)(double))
{ // 中差微分
    return 0.5 * ( fx(x+h) - fx(x-h) ) / h;
}

int main()
{
    double x = 1.0, h=0.01, delta;
    double ans = cos(x); // 答案
    double cal;

    cal = FordDiff(x, h, func), delta = cal - ans;
    printf("FordDiff : %lf, delta = %lf\n",cal,delta);
    cal = BackDiff(x, h, func), delta = cal - ans;
    printf("BackDiff : %lf, delta = %lf\n",cal,delta);
    cal = MidDiff(x, h, func), delta = cal - ans;
    printf("MidDiff  : %lf, delta = %lf\n",cal,delta);
    return 0;
}
輸出結果
FordDiff : 0.536086, delta = -0.004216
BackDiff : 0.544501, delta = 0.004198
MidDiff  : 0.540293, delta = -0.000009

沒有留言:

張貼留言

WOKWI LED + MQTT Node-Red SQLite

WOKWI LED + MQTT Node-Red SQLite const char *mqtt_broker = "broker.mqtt-dashboard.com" ; const char *topic1 = "alex9ufo/e...