1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Python]前進差分・後退差分・中心差分で数値微分を求める方法

Last updated at Posted at 2025-02-12

はじめに

数値微分は、数字や数値解析で重要な手法です。特に前進差分(Forward Difference)、後退差分(Backward Difference)、中心差分(Central Difference)は。数値的に導関数を近似する際に使われます。今回Pythonを用いて、これら3つの差分法を実装し、導関数の近似と誤差を計算する方法を紹介します。

差分法の概要

  1. 前進差分(Forward Difference)
    image.png

  2. 後退差分(Backward Difference)
    image.png

  3. 中心差分(Central Difference)
    image.png

中心差分は精度が高く、誤差が前進差分や後退差分よりも小さくなることが多いです。これらをPythonで実装し、結果を比較します。

実装コード

differential.py
import numpy as np

# 関数 f(x) を定義
def f(x):
    return -x**3 + 3*x + 2

# 前進差分
def forward_difference(x, h):
    return (f(x + h) - f(x)) / h

# 後退差分
def backward_difference(x, h):
    return (f(x) - f(x - h)) / h

# 中心差分
def central_difference(x, h):
    return (f(x + h) - f(x - h)) / (2 * h)

# 相対誤差を計算
def relative_error(estimated, exact):
    return abs(estimated - exact) / abs(exact)

# 定数
h = 0.1  # 微小量 h
x = 0.5  # 微分点 x
exact_derivative = -3 * x**2 + 3  # 正確な微分値 f'(x)

# 差分法の計算
forward = forward_difference(x, h)
backward = backward_difference(x, h)
central = central_difference(x, h)

# 相対誤差の計算
forward_error = relative_error(forward, exact_derivative)
backward_error = relative_error(backward, exact_derivative)
central_error = relative_error(central, exact_derivative)

# 結果を丸める
forward_rounded = round(forward, 2)
backward_rounded = round(backward, 2)
central_rounded = round(central, 2)
forward_error_rounded = round(forward_error, 3)
backward_error_rounded = round(backward_error, 3)
central_error_rounded = round(central_error, 3)

# 結果の表示
print("(1) 前進差分 f'(0.5):", forward_rounded)
print("(2) 前進差分 ε(0.5):", forward_error_rounded)
print("(3) 後退差分 f'(0.5):", backward_rounded)
print("(4) 後退差分 ε(0.5):", backward_error_rounded)
print("(5) 中心差分 f'(0.5):", central_rounded)
print("(6) 中心差分 ε(0.5):", central_error_rounded)

実行結果

(1) 前進差分 f'(0.5): 2.09  
(2) 前進差分 ε(0.5): 0.071  
(3) 後退差分 f'(0.5): 2.39  
(4) 後退差分 ε(0.5): 0.062  
(5) 中心差分 f'(0.5): 2.24  
(6) 中心差分 ε(0.5): 0.004  

結果の考察

  • 前進差分と後退差分の相対誤差はそれぞれ0.071,0.062であり、比較的小さいですが、まだ精度の向上が可能
  • 中心差分は誤差が0.004と非常に小さく、精度の高い結果を提供
    これらの結果から、精度が重要な場合は中心差分を使用することが推奨されます。

まとめ

本記事では、Pythonを使った数値微分の3つの差分法を実装し、誤差の比較を行いました。これらの微分方程式を解く際にも重要な基礎知識となりますので、ぜひ他の関数でも試してみてください。最後まで読んでくださり、ありがとうございました。もし改善点や質問があれば、ぜひコメントしてください!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?