[Numpy-discussion] Data types in Numerical Python

Anne Archibald peridot.faceted@gmail....
Sun Oct 12 10:26:05 CDT 2008


2008/10/12 Linda Seltzer <lseltzer@alumni.caltech.edu>:
>> Here is an example that works for any working numpy installation:
>>
>> import numpy as npy
>> npy.zeros((256, 256))
> This suggestion from David did work so far, and removing the other import
> line enabled the program to run.
> However, the data types the program used as defaults for variables has
> changed, and now I am getting error messages about data types.  It seems
> that some variables are getting a default designation as floats.  Before I
> installed numpy and needed 2-D arrays, the program was working with the
> default types, and I did not have to specify types.
> Is there a clear tutorial that describes a means to assign data types for
> each variable as in C, so that I don't obtain error messages about data
> types?

Python is a dynamically-typed language (unlike C), so variables do not
have type. That is, a variable can refer to an object of any type; if
you need to know what type of object a variable currently refers to
you must inspect the object. You may want to go through one of the
brief introduction-to-python tutorials that are on the python website
just to get comfortable with the language. (For example, understanding
the meaning and syntax of import statements.)

When you create a numpy array, you can specify its type. You can also
explicitly or implicitly convert the types of numpy arrays. I
recommend you select a data type, let's say np.uint32, and make sure
various arrays are created containing that type:

np.zeros((m,n),dtype=np.uint32)
np.arange(10,dtype=np.uint32)
x.astype(np.uint32)
np.array([1,2,3,4.5], dtype=np.uint32)

et cetera. Most operations (addition, multiplication, maximum) will
preserve the data type of arrays they are given (but if you supply two
different data types numpy will attempt to choose the "larger").

> Because I am simulating code for a DSP processor, the data types I need
> are unsigned bytes, unsigned 32-bit ints, and signed 32-bit ints.  In some
> cases I can use unsigned and signed 16-bit ints.
> Also, what data types are valid for use with local operations such as
> exclusive or?

The numpy data types you want are described by "dtype" objects. These
can in principle become quite complicated, but the ones you need are
given names already:

np.uint8
np.uint32
np.int32
np.uint16
np.int16

You can specify any of these as "dtype=" arguments to the various
numpy functions. If you need really rigid typing, python may not be
the ideal language for you.

Good luck,
Anne


More information about the Numpy-discussion mailing list