[Pyrex] newbie question: error using pyrex

Robert Bradshaw robertwb at math.washington.edu
Tue Sep 18 20:36:17 CEST 2007


In Cython, this code should be even faster, and cleaner to read too,  
as follows:

- Robert


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

cdef extern from "Python.h":
     int PyObject_Length(object obj) except -1


def pofr(vectors):
     distances = []
     cdef int i, j, n
     cdef double ax, ay, az, bx, by, bz
     n = len(vectors)
     for i from 0 <= i < n:
         a = vector[i]
         ax, ay, az = a[0], a[1], a[2]
         for j from i+1 <= j < n:
             b = vector[j]
             bx, by, bz = b[0], b[1], b[2]
             dist = sqrt((ax-bx)*(ax-bx) +
                                (ay-by)*(ay-by) +
                                (az-bz)*(az-bz))
             PyList_Append(distances, dist)
     return distances


On Sep 18, 2007, at 8:22 AM, Sven Berkvens-Matthijsse wrote:

>> 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
>
> _______________________________________________
> Pyrex mailing list
> Pyrex at lists.copyleft.no
> http://lists.copyleft.no/mailman/listinfo/pyrex




More information about the Pyrex mailing list