c++ - How to iterate an array in Python pointer-likely and efficiently? -
i quite new in python, iterate array calculate next element based on previous elements. can think of in c++ manner how achieve in python using numpy or pandas? know similar method using shifting way seems not efficient.
the following simple fibonacci example:
int arr[10]; arr[0] = 1; arr[1] = 1; int* pt = &arr[2]; <--get iterator moving pointer int count = 8; while (count > 0) { *pt = pt[-1] + pt[-2]; <--access previous k element based on current index count--; pt++; <--point next element } (int = 0; < 10; i++) cout << arr[i] << endl;
list:
l = [1, 1] while len(l) != 10: l.append(l[-1] + l[-2]) <--but have append element every time print l
the direct numpy
immitation of c++ is
arr=np.ones((10,)) in range(2,arr.shape[0]): arr[i]=arr[i-1]+arr[i-2]
producing:
array([ 1., 1., 2., 3., 5., 8., 13., 21., 34., 55.])
this isn't efficient way of doing in numpy
, it's discussion start.
most fast numpy
operations use compiled c code, , results buffered, tricky perform fast sequential operations. best think of numpy operations acting in parallel, on terms of array @ once (without preference order). exceptions ufunc
cumsum
, cumprod
- cumulative processes, , unbuffered ufunc
called at
. i'd have play around see if there's way of calculating series 1 of these tools.
another option implement calculation in c or c++ , link it. cython
convenient tool doing this.
http://wiki.scipy.org/cookbook/ctypes#head-6a582bd7b101bca0df6e5631a06e2d1d76e35a95 example of using ctypes
, c
code numpy
calculate fibonachi.
http://numpy-discussion.10968.n7.nabble.com/vectorizing-recursive-sequences-td35532.html describes cleaver way of calculating series. depends on ufunc
taking out
array. author admits depends on implementation details, calculation not buffered.
arr=np.ones((10,)) np.add(arr[:-2], arr[1:-1], out=arr[2:])
the elements of 1st 2 arguments added, element element, , stored in out
array.
arr[2:] = arr[:-2]+arr[1:-1]
does not work because of buffering
http://docs.cython.org/src/tutorial/cython_tutorial.html#fibonacci-fun
is cython example of fibonacci. should fast, prints results, opposed accumulating them in array. still shouldn't hard cython/c version stores results in cython array or memoryview.
here's cython
script, can saved pyx
, compiled , imported. refined usefulness , speed, it's enough test concept:
import numpy np narr = np.ones((10,), dtype=np.dtype("i")) cdef int [:] narr_view = narr cpdef void fib(int[:] arr): = arr.shape[0] in range(2,i): arr[i] = arr[i-2]+arr[i-1] fib(narr_view) print 'fib arr:', narr
Comments
Post a Comment