如何区分函数的功能?

时间:2017-10-26 21:58:39

标签: python function differentiation automatic-differentiation

我试图区分z(x)w.r.t。 x使用ad库,我知道y(x)和z(y)。如果我不能分析地找到z(x),我该如何进行区分?换句话说,我试图避免链规则计算,如下所示:

from ad import gh

def y(x):
    return 2*x

def z(y):
    return 3*y

dzdy,hy = gh(z)
dydx,hz = gh(y)

x0 = 0 # does not matter for this example
dydx_x0 = dydx(x0)

y0 = y(x0)
dzdy_y0 = dzdy(y0)

dzdx_x0 = dzdy_y0[0] * dydx_x0[0]

print(dzdx_x0)    # dz/dx = dz/dy*dy/dx = 3*2 = 6

1 个答案:

答案 0 :(得分:2)

def z_of_x(x):
    return z(y(x))

gradient, hessian = gh(z_of_x)

只需定义一个按z计算x的函数,并像往常一样应用自动微分。