Thanks. Your version seems much more elegant def sqrv(x): return x * x I didn't know pythran would produce an element-wise iteration over the whole array from this code. On Fri, Sep 5, 2014 at 8:18 AM, serge Guelton <sguelton@xxxxxxxxxxxxx> wrote: > On Fri, Sep 05, 2014 at 07:01:27AM -0400, Neal Becker wrote: > > What is the best way to write a dimension-independent function? For > example, > > suppose I want to apply the function "sqr" element-wise to an > array > > of any number > > of dimensions N. > > > > I see one way is to explicitly instantiate the function for each desired > number > > of dimensions: > > > > > import numpy as np > > #pythran export sqr(float64[]) > > #pythran export sqr(float64[][]) > > def sqr (x): > > size = x.shape[0] > > y = np.empty_like (x) > > for i in range (size): > > y[i] = x[i] * x[i] > > return y > > That's the way it should be :-/ > > I tried this: > > import numpy as np > #pythran export sqr(float64[]) > #pythran export sqr(float64[][]) > #pythran export sqrv(float64[]) > #pythran export sqrv(float64[][]) > #pythran export sqr(float32[]) > #pythran export sqr(float32[][]) > #pythran export sqrv(float32[]) > #pythran export sqrv(float32[][]) > def sqr(x): > size = x.shape[0] > y = np.empty_like (x) > for i in range(size): > y[i] = x[i] * x[i] > return y > def sqrv(x): > return x * x > > compiled with: > > pythran -DUSE_BOOST_SIMD -march=native sqr.py > > and benchmarked with: > > python -m timeit -s 'import numpy as np ; r = > np.asarray(np.random.rand(1000,1000), dtype=np.float64); import sqr' > 'sqr.sqrv(r)' > > I end up with pythran performing roughly as fast as numpy for the > vectorized version, faster when using explicit loops, and faster on > float32 thanks to vectorisation. > > -- *Those who don't understand recursion are doomed to repeat it*