By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,091 Members | 1,917 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,091 IT Pros & Developers. It's quick & easy.

Rounding the elements of a Python array (numarray module)

P: n/a
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(numarray.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

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
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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.google. 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 discussion thread is closed

Replies have been disabled for this discussion.