gemath Examples: Array Creation and Information

Description

This web page provides examples of using various gemath array manipulation functions.

For more information see the module listing documentation. Or, for any command cmd, type help(cmd) at the Python prompt to get the docstring documentation.

Import Statements

In all the examples, assume the following import statements have been made:

>>> import Numeric as N
>>> import gemath as G

Creating Arrays

Often you'll want to create an array filled with the equivalent 1-D indices (i.e. the address an element would have if the array was ravel'ed). Numeric's arange function does this for vectors:

>>> a = N.arange(6)
>>> a
[0,1,2,3,4,5,]
>>> a = N.arange(6.0)
>>> a
[ 0., 1., 2., 3., 4., 5.,]

How can you do this for arrays of arbitrary dimension? The gemath dindgen, findgen, and lindgen functions do this. They have the same syntax and produce the same results, with the only difference being that dindgen produces a double-precision floating array, findgen a single-precision floating array, and lindgen a long integer array:

>>> a = G.findgen(6)
>>> a
[ 0., 1., 2., 3., 4., 5.,]
>>> a = G.findgen((2,3))
>>> a
[[ 0., 1., 2.,]
 [ 3., 4., 5.,]]
>>> a = G.findgen((3,2))
>>> a
[[ 0., 1.,]
 [ 2., 3.,]
 [ 4., 5.,]]

If the argument for *indgen is scalar, a rank 1 vector is created with that number of elements. If the argument is a tuple, an array is created with a shape give by that tuple.

Safe Comparison For Equality

Because floating point numbers are not exactly represented in binary computers, you have to be careful when comparing floating point numbers. Numeric provides the function allclose which checks whether two arrays (or one array and a scalar) are element-wise "equal" to each other. If the arrays are integer, exact comparison is used. If they are floating, safe comparisons are done.

has_close: In gemath the has_close function does an element-wise comparison of an array to a scalar. If any of the elements equals the scalar, 1 is returned; otherwise 0 is returned. Safe comparison is used if the type is floating:

>>> a = G.findgen(6)
>>> a
[ 0., 1., 2., 3., 4., 5.,]
>>> G.has_close(a, 2.)
1
>>> G.has_close(a, 2.00001)
1
>>> G.has_close(a, 2.0001)
0

where_close: If you want produce a mask showing which elements of an array are equal to another array (or an array and/or scalar combination), you can use the where_close function. Again, if either input is floating, safe comparisons are used. If the inputs are all integer, strict comparison is used:

>>> a = G.findgen(6)
>>> a
[ 0., 1., 2., 3., 4., 5.,]
>>> G.where_close(a, 2.00001)
[0,0,1,0,0,0,]
>>> G.where_close(a, 2.0001)
[0,0,0,0,0,0,]
>>> b = N.array([1., 3., 2., -2., 4., 5.])
>>> G.where_close(a, b)
[0,0,1,0,1,1,]

Return to gemath Index.
Return to Johnny Lin's Python Library.

Valid HTML 4.01! Valid CSS! Updated: April 27, 2004 by Johnny Lin <email address>. License.