python - 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 个元素的向量吗?我究竟做错了什么?
解决方案
推荐阅读
- sql - 在视图中将字符串转换为日期
- macos - dyld:库未加载:@rpath/libnetcdf.13.dylib ...原因:找不到图像:MacOS Big Sur 上的 GMT
- angular - 使用 Angular 10 时的 CSP 阻止样式和脚本
- debian - ZFS:如何降低或防止 txg_sync 的频率
- elasticsearch - elasticsearch:cluster_block_exception TOO_MANY_REQUESTS/12/index 只读/允许删除(api)
- python - 为什么子图在 plt 和 sns 中表现不同
- grpc - GRPC 如何处理出现多次的指针?
- javascript - 有没有办法在不提示上述权限的情况下检测 javascript 中的浏览器权限(特别是相机和麦克风)?
- xml - 如何使用 XSD 禁止元素值中的内容
- android - 如何使用 ExternalStorageStats