[Numpy-discussion] API tricks any my new "clip" function

Jon Saenz jsaenz at wm.lc.ehu.es
Wed Aug 29 16:16:19 CDT 2001


On Wed, 29 Aug 2001, Chris Barker wrote:

> A) Are there any tricks to making a function work with multiple types? I
> currently have it working with only double arrays, but it would be great
> for it ot be universal (and it could then be added to the main NumPy
> distribution, I suppose) I seem tohave to typecast the data to do the
> comparison I want, so I can't figure out how to make it general. For
> example, I have this line:
> 
> if (*(double *)(Array->data + i*elementsize) > *(double *)(Max->data +
> i*elementsize))
> {
>           *(double *)(Array->data + i*elementsize) = *(double
> *)(Max->data + i*elementsize) ;
> }
> 
> How could I do that without the explicit typecasts? I'm pretty sure I
> could make the rest of the routine general.
Some time ago, I used a union like:
typedef union {
short *sdata;
int *idata;
long *ldata;
float *fdata;
double *ddata; 
/* And so on */
} MyNumPyUnion;

Then, you can assign (and CAST) the data field of the NumPy array
according to the typecode of the array, like in:

MyNumPyUnion theunion;

theunion.fdata=(float*) thenumpyarray->data; /* If it is a Float32 */

Finally, you use  sdata, idata, ldata, fdsata and so on to iterate
dereferencing accordingly, depending on the typecode of the array.

It is a nightmare to write this code, but I can not imagine of any other
approach. May be other developers can help you with a better approach.

Hope this helps.


Jon Saenz.				| Tfno: +34 946012470
Depto. Fisica Aplicada II               | Fax:  +34 944648500
Facultad de Ciencias.   \\ Universidad del Pais Vasco \\
Apdo. 644   \\ 48080 - Bilbao  \\ SPAIN







More information about the Numpy-discussion mailing list