python - numpy.gradient() 似乎产生错误的边界值(使用一阶差分)

标签 python numpy

函数 numpy.gradient() (numpy 1.9.0) 似乎有一个关于它如何计算边界(开始和结束)值的问题(我知道它使用一阶差分,而计算中心值使用中心差异)。例如考虑以下示例:

import numpy as np
arr = np.array([1, 2, 4])
arrgrad = np.gradient(arr)

我希望 arrgrad 获得这些值

[ 1.   1.5  2. ]

arrgrad[0] = (2-1)/1 = 1
arrgrad[1] = (4-1)/2 = 1.5  
arrgrad[2] = (4-2)/1 = 2

但我得到了结果

[ 0.5  1.5  2.5]

然而,1.8.1 版(从 https://github.com/numpy/numpy/blob/v1.8.1/numpy/lib/function_base.py 获得)的 numpy.gradient() 的行为似乎产生了正确的结果。

上面描述的错误行为是错误的结果吗? (我使用的是 Python 3.4.2,64 位。)

最佳答案

显然,332d628 在 1.8.1 和 1.9.0 之间更改了计算梯度的方式| ,因此边界元素现在也使用二阶精确近似计算,而以前它们仅是一阶精确。

但是,numpy 网站上的文档不包括 1.9.0 文档,只包括 1.8.1,因此要查看正确的文档,您可以使用 np.source(np.gradient)print(np.gradient.__doc__)

关于python - numpy.gradient() 似乎产生错误的边界值(使用一阶差分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26361007/

相关文章:

python - 从数据框中的列值返回列表

python - 如何在 numpy 数组中添加维度? (125, 125) 至 (125, 125, 1)

python - numpy 中的均方根以及 numpy 矩阵和数组的并发症

python - AttributeError: 'Series' 对象没有属性 'items'

python - 在 Pandas DataFrame 绘图中指定 y 数组和绘图标签会更改数据框的索引标签/名称吗?

python - 使用 lxml.html 的 cssselect 选择 ID 属性中带有冒号的元素

python - 物理转置大型非方 numpy 矩阵

python - 填充numpy数组中的相邻元素

python - 在 with None : what if it's an array? 之后定义默认参数

Python PIL : font weight and style