Skip to content

Instantly share code, notes, and snippets.

@disconnect3d
Last active February 8, 2017 10:33
Show Gist options
  • Save disconnect3d/089c63b6fc1dd1fd2afb678549658daf to your computer and use it in GitHub Desktop.
Save disconnect3d/089c63b6fc1dd1fd2afb678549658daf to your computer and use it in GitHub Desktop.
%%cython
# Minkowski Distance with p=0.5
# based on scikit-learn MinkowskiDistance cython's class
# https://github.com/scikit-learn/scikit-learn/blob/cbd3bca20f1d19461011b5f59d9416669eb30535/sklearn/neighbors/dist_metrics.pyx#L524
from libc.math cimport fabs, sqrt, pow
cimport numpy as np
from typedefs cimport DTYPE_t, ITYPE_t, DITYPE_t
cdef inline DTYPE_t minkowski_05(DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size) nogil except -1:
cdef DTYPE_t d = 0
cdef np.intp_t j
for j in range(size):
d += sqrt(fabs(x1[j] - x2[j]))
return pow(d, 2.0)
import cython
import numpy as np
@cython.boundscheck(False)
@cython.wraparound(False)
def minkowski_05_py(np.ndarray[np.float64_t, ndim=1, mode = 'c'] x, np.ndarray[np.float64_t, ndim=1, mode = 'c'] y):
return minkowski_05(&x[0], &y[0], x.shape[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment