Scipy.integrateによる数値積分
メニューを表示するにはスワイプしてください
数値積分は、曲線下の面積を計算したり、解析的な解が存在しない方程式を解いたりするための手法。科学技術計算では、定積分の評価や常微分方程式(ODE)の解法が必要となる場面が多く、正確な解が不明または非常に複雑な場合がある。SciPyの scipy.integrate モジュールは、これらのタスクに対して強力かつ使いやすいツールを提供し、わずか数行の python コードで数値積分やODEの数値解法を実現可能。
1234567891011from scipy import integrate import numpy as np # Define the function to integrate def f(x): return np.sin(x) # Compute the definite integral of sin(x) from 0 to pi result, error = integrate.quad(f, 0, np.pi) print("Integral result:", result) print("Estimated error:", error)
1234567891011121314151617181920212223from scipy.integrate import solve_ivp import numpy as np import matplotlib.pyplot as plt # Define the ODE: dy/dt = -2y def dydt(t, y): return -2 * y # Initial condition y0 = [1] # Time span for the solution t_span = (0, 5) # Solve the ODE solution = solve_ivp(dydt, t_span, y0, t_eval=np.linspace(0, 5, 100)) # Plot the solution plt.plot(solution.t, solution.y[0]) plt.xlabel("t") plt.ylabel("y(t)") plt.title("Solution of dy/dt = -2y with y(0) = 1") plt.show()
scipy.integrate.quad を使用すると、関数は積分の計算値と誤差の推定値の両方を返します。上記の例では、sin(x) を 0 から π まで積分すると、2 に非常に近い結果が得られ、これは厳密な解析解と一致します。これにより、数値積分ルーチンの精度と信頼性の両方が示されます。
常微分方程式の場合、scipy.integrate.solve_ivp は指定された区間で解を計算します。ODE の例では、初期条件 dy/dt = -2y を持つ方程式 y(0) = 1 は指数関数的減衰を表します。解は y が時間とともに滑らかに減少する様子を示し、簡単なプロットでこれを可視化できます。出力は期待される解析解 y(t) = exp(-2t) と一致します。
1. SciPy で定積分に使用される関数はどれですか?
2. scipy.integrate.solve_ivp は何を解きますか?
3. なぜ数値積分は科学技術計算において重要なのですか?
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 1
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 1