【C言語】微分・偏微分の計算と導関数のグラフ表示
目次
微分の基本概念
微分とは、関数の変化率を求める操作です。関数 \( f(x) \) の微分係数は、次の極限で定義されます:
\[ f'(x) = \lim_{h \to 0} \frac{f(x+h) – f(x)}{h} \]
ここで、\( h \) を十分小さな値に設定し、関数の変化率を近似することが数値微分の基本となります。
数値微分の方法
数値微分では、離散的なデータを用いて微分を近似します。よく用いられる手法には以下の3つがあります:
前進差分
\[ f'(x) \approx \frac{f(x+h) – f(x)}{h} \]
後退差分
\[ f'(x) \approx \frac{f(x) – f(x-h)}{h} \]
中心差分
\[ f'(x) \approx \frac{f(x+h) – f(x-h)}{2h} \]
中心差分のほうが精度が高く、通常の数値微分ではこの方法がよく使用されます。
偏微分の計算
2変数関数 \( f(x, y) \) の偏微分は、ある変数を固定して他方の変数について微分を行います:
\( x \) についての偏微分: \[ \frac{\partial f}{\partial x} = \lim_{h \to 0} \frac{f(x+h, y) – f(x, y)}{h} \]
\( y \) についての偏微分: \[ \frac{\partial f}{\partial y} = \lim_{h \to 0} \frac{f(x, y+h) – f(x, y)}{h} \]
導関数のグラフ表示
C言語単体ではグラフを直接描画することは困難ですが、データを出力して Python や gnuplot などを使用すると可視化できます。例えば、C言語で微分値を計算し、CSV形式で出力し、それを Python でプロットする方法があります。
C言語による具体例
数値微分の実装
#include <stdio.h>
#include <math.h>
double function(double x) {
return x * x; // f(x) = x^2
}
double derivative(double (*f)(double), double x, double h) {
return (f(x + h) - f(x - h)) / (2 * h);
}
int main() {
double x = 2.0;
double h = 1e-5;
printf("f'(%.2f) = %.5f\n", x, derivative(function, x, h));
return 0;
}
偏微分の実装
#include <stdio.h>
#include <math.h>
double function(double x, double y) {
return x * x + y * y;
}
double partial_derivative_x(double (*f)(double, double), double x, double y, double h) {
return (f(x + h, y) - f(x - h, y)) / (2 * h);
}
double partial_derivative_y(double (*f)(double, double), double x, double y, double h) {
return (f(x, y + h) - f(x, y - h)) / (2 * h);
}
int main() {
double x = 1.0, y = 2.0;
double h = 1e-5;
printf("∂f/∂x at (%.2f, %.2f) = %.5f\n", x, y, partial_derivative_x(function, x, y, h));
printf("∂f/∂y at (%.2f, %.2f) = %.5f\n", x, y, partial_derivative_y(function, x, y, h));
return 0;
}
グラフ出力用のデータ生成
#include <stdio.h>
#include <math.h>
double function(double x) {
return sin(x);
}
double derivative(double (*f)(double), double x, double h) {
return (f(x + h) - f(x - h)) / (2 * h);
}
int main() {
double h = 1e-5;
FILE *file = fopen("data.csv", "w");
fprintf(file, "x,f(x),f'(x)\n");
for (double x = -10; x <= 10; x += 0.1) {
fprintf(file, "%.2f,%.5f,%.5f\n", x, function(x), derivative(function, x, h));
}
fclose(file);
printf("データを data.csv に出力しました。\n");
return 0;
}
このプログラムで出力された CSV を Python で可視化できます:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("data.csv")
plt.plot(df["x"], df["f(x)"], label="f(x)")
plt.plot(df["x"], df["f'(x)"], label="f'(x)", linestyle="dashed")
plt.legend()
plt.show()
これで C 言語を用いた微分計算とグラフ表示が可能になります。