Skip to content

Instantly share code, notes, and snippets.

@leifdenby
Created August 1, 2013 09:56
Show Gist options
  • Save leifdenby/6130043 to your computer and use it in GitHub Desktop.
Save leifdenby/6130043 to your computer and use it in GitHub Desktop.
Method for performing numpy vectorized integration of a function over a discrete range, at several points.
import numpy as np
def cellAverageIntegrator1D(f, x0, dx, N=10):
"""
This function calculates the integral of a given (numpy vectorized)
function f over the interval [x0-dx/2., x0+dx/2.]. The number of discrete
points may be set using N.
The argument x0 may be a numpy array of discrete points (e.g. cell-centers)
to evaluate the integral. Because everything is vectorized this function
executes very fast.
"""
x = x0 + np.outer(np.linspace(-dx/2., +dx/2., N), np.ones((len(x0),)))
return np.sum(f(x), axis=0)/N
if __name__ == "__main__":
# 1D test
f = np.sin
dx = 0.1
x0 = np.array([0.3, 0.4, 0.5])
F = lambda x: (np.cos(x-dx/2.) - np.cos(x+dx/2.))/dx
for N in [2**n for n in range(20)]:
F_int = cellAverageIntegrator1D(f=f, x0=x0, dx=dx, N=N)
print N, F_int - F(x0), f(x0) - F(x0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment