Rounding the elements of a Python array (numarray module)

C

Chris P.

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 likebut 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 soI 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

P.S. Here's my "bad function"

# 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.shape) == 3:
(depths,rows,columns) = 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
 
C

Chris P.

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
aoccurred 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top