[Pyrex] newbie question: error using pyrex

Sven Berkvens-Matthijsse sven at pyrex.berkvens.net
Tue Sep 18 17:22:44 CEST 2007


> Thanks Sven,

Hello Christian,

> the code is working now. Now I hope it runs a bit faster ...

A bit probably, but this should be even faster (because it converts
the Python objects to floats only once and uses the Python API
directly). If you're concern is speed and not
readability/maintainability, then try this version:



cdef extern from "math.h":
    float sqrt(float)

cdef extern from "Python.h":
    int PyObject_Length(object obj) except *
    object PyList_GetItem(object the_list, int the_index)
    int PyList_Append(object the_list, object to_add) except -1
    float PyFloat_AsDouble(object the_number) except *

def pofr(vectors):
    cdef int i
    cdef int j
    cdef int n
    cdef object a
    cdef object b
    cdef object distances
    cdef float ab0
    cdef float ab1
    cdef float ab2

    distances = []
    n = PyObject_Length(vectors)
    for i from 0 <= i < n:
        for j from i+1 <= j < n:
            a = PyList_GetItem(vectors, i)
            b = PyList_GetItem(vectors, j)
            ab0 = PyFloat_AsDouble(PyList_GetItem(a, 0)) - \
                  PyFloat_AsDouble(PyList_GetItem(b, 0))
            ab1 = PyFloat_AsDouble(PyList_GetItem(a, 1)) - \
                  PyFloat_AsDouble(PyList_GetItem(b, 1))
            ab2 = PyFloat_AsDouble(PyList_GetItem(a, 2)) - \
                  PyFloat_AsDouble(PyList_GetItem(b, 2))
            dist = sqrt(ab0 * ab0 + ab1 * ab1 + ab2 * ab2)
            PyList_Append(distances, dist)
    return distances

> Regards,
> Christian

-- 
With kind regards,
Sven Berkvens-Matthijsse



More information about the Pyrex mailing list