首页 > 解决方案 > python中的数值导数

问题描述

我在计算两个变量的函数的导数时遇到问题。函数是这样的: (Z1_i - Z1_(i-1))^2+(Z2_i - Z2_(i-1))^2-L^2

$L$是维度向量($z1_i$ and $z2_i$)=11,config是起点和终点的配置,代码如下:

def con (zz, L, config):
    # zz = [z ^ 1_1, z ^ 2_1, z ^ 3 ..... z ^ N_1, z ^ 1_2, z ^ 2_2, .... z ^ n_2]
    nL = len (L)
    res = np.zeros (nL)
    zzM = np.zeros ((2, nL +1))
    zzM [:, 0] = config ['a']
    zzM [:, 1: -1] = zz.reshape (2, -1)
    zzM [:, - 1] = config ['b']
    for i, l in enumerate (L ['l']):
        res [i] = sum ((zzM [:, i + 1] - zzM [:, i]) ** 2) - l ** 2

    return res

遵循数值导数公式:

def numGrad (xx, f):
    n = len (xx)
    eps = 1e-7
    ngrad = np.ones ((2, n))
    for i in range (n):
        xxz = xx.copy ()
        xxz [i] + = eps
        ngrad [i] = (f (xxz) - f (xx)) / eps
    return ngrad



fc = lambda zz: con (zz, l1, config1)

numGrad (zz, fc)

我得到这个向量:

numGrad (zz, fc)
Oct [243]:
array ([0., 0., 0., 0., 0.,
        0., 0., 0., 0., -0.38851931,
        0.7123603])

我的问题是,知道 $Z1_i$ 和 $Z2_i$ 包含 11 个变量,这个函数的导数不会是 22 个元素的向量吗?我究竟做错了什么?

标签: pythonnumerical-methodsderivative

解决方案


推荐阅读