Skip to content

Instantly share code, notes, and snippets.

@gary136
Last active November 29, 2019 09:38
Show Gist options
  • Select an option

  • Save gary136/8eb42822cf19ee41a47df24632b95566 to your computer and use it in GitHub Desktop.

Select an option

Save gary136/8eb42822cf19ee41a47df24632b95566 to your computer and use it in GitHub Desktop.
gd1.py
def test(xlist):
# xlist is the list of the variables we have, and in this particular instance we have two variables
return 2*xlist[0]**2+3*xlist[0]*xlist[1]+5*xlist[1]**2
# functions
def partial_derivative(f, x_list, odr, epsilon = 1e-6, **kargs):
# 此為模擬偏微分會有少量誤差
h_list = x_list.copy()
h_list[odr] = x_list[odr] + epsilon
fx = f(x_list, **kargs)
fh = f(h_list, **kargs)
return (fh - fx) / epsilon
def gradient(f, x_list, **kargs):
grd = [partial_derivative(f, x_list, odr, **kargs) for odr in range(len(x_list))]
return grd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment