473,897 Members | 3,371 Online

# Rounding the elements of a Python array (numarray module)

Hi. I have a very simple task to perform and I'm having a hard time
doing it.

Given an array called 'x' (created using the numarray library), is
there a single command that rounds each of its elements to the nearest
integer? I've already tried something like
x_rounded = x.astype(numarr ay.Int) but that only truncates each element (i.e. '5.9' becomes '5').

I've read over all the relevant numarray documentation, and it
mentions a bunch of Ufuncs that are available - there's 'floor' and
'ceil', but no 'round'. And when I try using the built-in function
'round' on an array like so x_rounded = round(x)

I get "TypeError: Only rank-0 numarray can be cast to floats."

So I created a bad function that uses nested loops, but my arrays are
600x600x3 elements (I'm doing some image processing after converting a
PIL Image to a numarray array) and it takes a REALLY long time. Has
anyone else had to do this, or knows of any tricks? Any help is
appreciated.

- Chris

# This code assumes that 'the_array' is a 3-dimensional array.
def ArrayRound(the_ array):
result = numarray.zeros( the_array.shape )
if len(the_array.s hape) == 3:
(depths,rows,co lumns) = the_array.shape
for depth in range(depths):
for row in range(rows):
for column in range(columns):
result[depth][row][column] = #continued
round(the_array[depth][row][column])
return result
Jul 18 '05 #1
1 3220
Soooo I wasn't sure if no one replied because a) this question was too
dumb or b) this question was too hard... it was definitely the former.
But I'll post the answer, anyway:

I forgot to keep in mind - when reading the documentation, assume that
a
from numarray import * occurred first.

So here's the way to do it: import numarray
a = numarray.array([1.6, 1.9, 2.1])
rounded_a = numarray.around (a)

and rounded_a then equals ([2., 2., 2.])

- Chris

ch************* *@utoronto.ca (Chris P.) wrote in message news:<3f******* *************** ****@posting.go ogle.com>... Given an array called 'x' (created using the numarray library), is
there a single command that rounds each of its elements to the nearest
integer?

Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.