python - Python。Scipy 数值导数
问题描述
不久前我发现scipy.misc.derivative
。
def derivative(func, x0, dx=1.0, n=1, args=(), order=3)
它的速度和精确度令人难以置信。所以,我决定弄清楚它是如何工作的。但是我没有完全看懂这个函数的代码,用在derivative
:
def central_diff_weights(Np, ndiv=1)
据我了解,该函数在高阶导数的展开中找到系数,但它是如何做到的呢?
来源: https ://github.com/scipy/scipy/blob/v0.18.0/scipy/misc/common.py#L179-L249
代码:
def central_diff_weights(Np, ndiv=1):
"""
Return weights for an Np-point central derivative.
Assumes equally-spaced function points.
If weights are in the vector w, then
derivative is w[0] * f(x-ho*dx) + ... + w[-1] * f(x+h0*dx)
Parameters
----------
Np : int
Number of points for the central derivative.
ndiv : int, optional
Number of divisions. Default is 1.
Notes
-----
Can be inaccurate for large number of points.
"""
if Np < ndiv + 1:
raise ValueError("Number of points must be at least the derivative order
+ 1.")
if Np % 2 == 0:
raise ValueError("The number of points must be odd.")
from scipy import linalg
ho = Np >> 1
x = arange(-ho,ho+1.0)
x = x[:,newaxis]
X = x**0.0
for k in range(1,Np):
X = hstack([X,x**k])
w = product(arange(1,ndiv+1),axis=0)*linalg.inv(X)[ndiv]
return w
解决方案
推荐阅读
- python - [Microsoft][ODBC Driver 17 for SQL Server]登录超时已过期 (0) (SQLDriverConnect)')
- c# - 无法从三元组将 0 分配给 c# 中的短变量
- influxdb - 在influx中使用flux语言修改系列数据
- python - 循环字符和整数
- arrays - 数组过滤不会改变 Crystal 中的数组
- node.js - 尝试纱线启动时出现奇怪的 IP - EADDRNOTAVAIL
- laravel - Unbale 为在 Laravel 上创建的 api 在 Swagger hub 上的 api doc 中提供授权
- c# - 将通用列表转换为 IEnumerable 列表以将其传递给 View
- selenium-webdriver - 使用 nbsp 定位元素
- python - 如何连接所有列表(每个列表都是我的 for 循环)