📌 目录
- 模块简介
- 数值积分(
quad
) - 定积分与不定积分
- 常微分方程求解(
odeint
) - 积分近似与矩形法、辛普森法
- 示例:物理问题中的微分方程求解
- 出站链接与参考资料
1. 模块简介
scipy.integrate
模块提供了数值积分和微分方程求解的功能,常用于物理、工程和生物学等领域的数学建模。
主要功能包括:
- 数值积分:单变量与多变量积分
- 常微分方程(ODE)求解:求解初值问题和边值问题
- 积分近似方法:矩形法、辛普森法、Gauss 求积法等
2. 数值积分(quad
)
quad
函数用于进行单变量函数的定积分计算,支持无限区间。
from scipy.integrate import quad
import numpy as np
# 被积函数
def integrand(x):
return np.exp(-x**2)
# 计算定积分
result, error = quad(integrand, 0, np.inf)
print(f"定积分结果:{result}, 误差估计:{error}")
该方法默认计算的是区间 [a, b]
内的定积分,可以通过返回的误差估计来判断结果的准确性。
3. 定积分与不定积分
定积分
result, error = quad(lambda x: np.sin(x), 0, np.pi)
print(f"定积分结果:{result}")
不定积分
使用 scipy.integrate
中的 odeint
进行常微分方程求解时,不定积分会在求解过程中自动使用。
4. 常微分方程求解(odeint
)
常微分方程(ODE)的求解是 scipy.integrate
中的一项重要功能,odeint
可以用来求解初值问题。
示例:简单的常微分方程
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
# 定义微分方程
def model(y, t):
dydt = -2 * y
return dydt
# 初始条件与时间范围
y0 = 1
t = np.linspace(0, 5, 100)
# 求解微分方程
sol = odeint(model, y0, t)
# 可视化解
plt.plot(t, sol)
plt.title("ODE 解:y'(t) = -2y")
plt.xlabel('时间 t')
plt.ylabel('y(t)')
plt.show()
微分方程的通用形式:
def model(y, t, params):
dydt = params[0] * y
return dydt
可以通过给 odeint
传递额外的参数,灵活地求解多类微分方程。
5. 积分近似与矩形法、辛普森法
SciPy 提供了不同的积分近似方法,以应对各种实际问题。
矩形法:
def rectangle_method(f, a, b, n):
x = np.linspace(a, b, n)
dx = (b - a) / n
return np.sum(f(x) * dx)
result = rectangle_method(lambda x: np.exp(-x**2), 0, np.inf, 1000)
print(f"矩形法计算结果:{result}")
辛普森法:
from scipy.integrate import simpson
x = np.linspace(0, np.pi, 100)
y = np.sin(x)
result = simpson(y, x)
print(f"辛普森法计算结果:{result}")
辛普森法比矩形法在计算效率和精度上都更优。
6. 示例:物理问题中的微分方程求解
示例:受迫摆的微分方程
def pendulum(y, t, b, c):
theta, omega = y
dydt = [omega, -b*omega - c*np.sin(theta)]
return dydt
y0 = [np.pi/4, 0] # 初始条件
t = np.linspace(0, 10, 100)
b = 0.25 # 阻尼系数
c = 5.0 # 振幅
sol = odeint(pendulum, y0, t, args=(b, c))
# 可视化角度与角速度
plt.plot(t, sol[:, 0], label="角度 θ(t)")
plt.plot(t, sol[:, 1], label="角速度 ω(t)")
plt.legend(loc="best")
plt.title("受迫摆的动态解")
plt.xlabel('时间 t')
plt.ylabel('解 y(t)')
plt.show()
此例模拟了一个受迫摆的动态行为,利用微分方程描述其角度和角速度随时间的变化。
🔗 出站链接与参考资料
📘 官方文档
scipy.integrate
官方手册:
https://docs.scipy.org/doc/scipy/reference/integrate.html
发表回复