[SciPy-dev] Default type behaviour of array

Fernando Perez Fernando.Perez at colorado.edu
Sat Nov 12 02:21:44 EST 2005


Jonathan Taylor wrote:
> Hi,
> 
> I have had quite a bit of success moving some of my R scripts to scipy. 
> Today I was creating a matrix of zeros and assigning some elements
> uniform distributed values from -1 to 1.  I couldnt figure out for quite
> a bit why my matrix remained zerod.  So I guess that is because zeros
> returns an int array by default.  I would have expected a float array by
> default.  Maybe there is a good reason for this though.
> 
> Also, maybe it should complain when you put floats into an integer array
> instead of just rounding the elements.  That is, maybe you should have
> to explicity round the elements?

I think that, while perhaps a bit surprising at first, this is one of those 
cases where you just have to 'learn to use the library'.  The point is that 
you should think of scipy arrays as C-style, strongly typed variables. 
Hopefully this C snippet will illustrate the issue:

abdul[~]> cat trunc.c
#include <stdio.h>

int main(void) {

    int n;
    float x;

    x = 3.14;
    n = x;

    printf("The float     x = %g\n",x);
    printf("The int   n = x = %d\n",n);

    return(0);
}

abdul[~]> ./trunc
The float     x = 3.14
The int   n = x = 3


Once you've declared your arrays as 'int' type, assignment will silently 
truncate.  In fact, this is often used as a feature in C (for table 
interpolation codes, for example).  I would not want a typecheck made on every 
assginment, as every layer of safety added to arrays carries a performance 
price.  Scipy arrays need to balance safety with speed, and in many cases it's 
a valid choice to err on the side of speed, at least I think so.  I recently 
lobbied for a change to the assignment semantics for the 'O' type arrays, but 
those are an altogether special type alread, and I think I managed to make a 
half-decent case that the existing behavior was just too bizarre to really be 
of any use.  But in this case, I'd rather keep the 'C-like' behavior so that 
we don't need more if statements in the internals.

At least that's my take on it, perhaps Travis or others will view it differently.

Cheers,

f




More information about the SciPy-Dev mailing list