我试图在numpy中实现一个数值梯度计算,作为cyipot中梯度的回调函数。我对numpy梯度函数的理解是,它应该返回基于finite different approximation的点计算的梯度。在
我不明白如何用这个模块来实现非线性函数的梯度。给出的样本问题似乎是一个线性函数。在
>>> f = np.array([1, 2, 4, 7, 11, 16], dtype=np.float)
>>> np.gradient(f)
array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ])
>>> np.gradient(f, 2)
array([ 0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ])
我的代码片段如下:
^{pr2}$另一个缺点是,我必须在几个点上计算x(它返回几个点的梯度) 在numpy/scipy中,是否有更好的选项可以在一个单个点处对梯度进行数值计算,这样我就可以将其作为回调函数来实现了?在
我想你对什么是数学函数和它的数值实现有一些误解。在
您应该将您的功能定义为:
现在您需要在特定的点计算函数,可以使用您提供的
np.mgrid
来实现。在如果要计算渐变,请使用
copy.misc.derivative
(https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.derivative.html)(注意dx的默认参数通常不好,请将其更改为1e-5
。在数值计算中,线性梯度和非线性梯度没有区别,只是对于非线性函数,梯度并非处处相同。在使用
np.gradient
实际上是从数组中的点计算梯度,函数的定义被f
的定义所隐藏,因此不允许在不同的点进行多个梯度计算。同样,使用你的方法会使你依赖于你的离散化步骤。在首先,一些警告:
还有更多:
还有一些替代品:
x >= y
+x <= y
可以来模拟等式约束)使用工具完成任务
完整的示例问题在Test Examples for Nonlinear Programming Codes中定义:
这里有一些代码,基于数值微分,解决你的测试问题,包括官方设置(函数,梯度,起点,边界…)
输出:
^{pr2}$关于代码
相关问题 更多 >
编程相关推荐