Skip to content

Instantly share code, notes, and snippets.

@terjehaukaas
Created June 12, 2019 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terjehaukaas/78cc08148d5e1dc2fb0127cc33966164 to your computer and use it in GitHub Desktop.
Save terjehaukaas/78cc08148d5e1dc2fb0127cc33966164 to your computer and use it in GitHub Desktop.
f and h by Finite Difference
# ------------------------------------------------------------------------
# The following functions are implemented in Python by Professor Terje Haukaas
# at the University of British Columbia in Vancouver, Canada. They are made
# freely available online at terje.civil.ubc.ca together with notes,
# examples, and additional Python code. Please be cautious when using
# this code; it may contain bugs and comes without any form of warranty.
#
# The following notation applies:
# F(x) = objective function, or merit function, relevant in optimization, not in root-finding
# f(x) = dF/dx = function whose root is sought
# h(x) = df/dx = d^2F/dx^2 = Hessian of objective function
# ------------------------------------------------------------------------
def f(x, F):
# Original function value
objective = F(x)
# Set the perturbation as a fraction of the x-value
dx = 0.001
if x != 0.0:
dx = dx * x
# Perturbed function value
dF = F(x + dx)
# Sought derivative
return (dF - objective) / dx
def h(x, F):
# Original function value
objective = F(x)
# Set the perturbation as a fraction of the x-value
dx = 0.001
if x != 0.0:
dx = dx * x
# Function value, perturbed forward
dFforward = F(x + dx)
# Function value, perturbed backward
dFbackward = F(x - dx)
# Sought derivative
return (dFforward - 2.0 * objective + dFbackward) / (dx**2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment