457,605 Members | 1,389 Online Need help? Post your question and get tips & solutions from a community of 457,605 IT Pros & Developers. It's quick & easy.

# How to "reduce" a numpy array using a costum binary function

 P: n/a I know there must be a simple method to do this. I have implemented this function for calculating a checksum based on a ones complement addition: def complement_ones_checksum(ints): """ Returns a complements one checksum based on a specified numpy.array of dtype=uint16 """ result = 0x0 for i in ints: result += i result = (result + (result >16)) & 0xFFFF return result It works, but is of course inefficient. My prfiler syas this is the 99.9% botteleneck in my applicaiton. What is the efficient numpy way to do this? No need to dwelve into fast inlining of c-code or Fortran and stuff like that although that may give further performance imporevements. Nov 13 '08 #1
3 Replies

 P: n/a It is always good to ask yourself a question. I had forgooten about the reduce function I guess this implementation from numpy import * def compl_add_uint16(a, b): c = a + b c += c >16 return c & 0xFFFF def compl_one_checksum(uint16s): return reduce(compl_add_uint16, uint16s, 0x0000) is somewhat better? But is it the best way to do it with numpy? In : hex(compl_add_uint16(0xF0F0, 0x0F0F)) Out: '0xffff' In : hex(compl_add_uint16(0xFFFF, 0x0001)) Out: '0x1' In : hex(compl_one_checksum(array([], dtype=uint16))) Out: '0x0' In : hex(compl_one_checksum(array([0xF0F0, 0x0F0F, 0x0001], dtype=uint16))) Out: '0x1L' Nov 13 '08 #2 