Skip to content

Instantly share code, notes, and snippets.

@dfm
Created August 13, 2012 19:51
Show Gist options
  • Save dfm/3343607 to your computer and use it in GitHub Desktop.
Save dfm/3343607 to your computer and use it in GitHub Desktop.
ctypes chi2 example by @jrwren
double chi2(double m, double b, double *x, double *y, double *yerr, int N) {
int n;
double result = 0.0, diff;
for (n = 0; n < N; n++) {
diff = (y[n] - (m * x[n] + b)) / yerr[n];
result += diff * diff;
}
return result;
}
#!/usr/bin/env python
from ctypes import *
libchi2 = cdll.LoadLibrary("libchi2.so.1.0.0")
ThreeDoubles = c_double * 3
m = c_double(2.0)
b = c_double(1.0)
x = ThreeDoubles( -1.0, 4.2, 30.6)
y = ThreeDoubles( -1.5, 8.0, 63.0)
y_err = ThreeDoubles( 1.0, 1.5, 0.6)
libchi2.chi2.restype = c_double
result = libchi2.chi2(m, b, x, y, y_err, 3)
print result
libchi2.so: chi2.o
gcc -shared -Wl,-soname,libchi2.so.1 -o libchi2.so.1.0.0 chi2.o -lc
chi2.o: chi2.c
gcc -fPIC -g -c -Wall chi2.c
@jrwren
Copy link

jrwren commented Aug 13, 2012

Thanks man, this is great. I loved your post and it made me look into ctypes which I'd been meaning to do.

@beaylott
Copy link

I made a version which uses the numpy.ctypes extensions which will work with arbitrarily long input/output vectors:
https://gist.github.com/3313315

@jkmacc-LANL
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment