MEric
MEric

Reputation: 966

Numpy Truncation?

I am implementing a program that uses the Python Numpy package. I am trying to modify the elements of an array so that I simply take elem[i][j] and set it to elem[i][j]/10. However, I keep getting some sort of truncation where the elements are set to 0 after the operation. Here is my code:

for  word in allwords:
    for x in xrange(wordarrays[word].shape[0]):
        for y in xrange(wordarrays[word].shape[1]):
            wordarrays[word][x][y]=wordarrays[word][x][y]/10

In my code wordarrays is a dictionary from strings to arrays. When I simply print wordarrays[word][x][y]/10 truncation is not a problem and the float division proceeds as expected. I have checked and the arrays all have dtype=float64 so that shouldn't be the problem. I also tried modifying the array through the method presented here using nditer

What is causing this truncation? Thanks for the help!


To give some more detail regarding my unusual output. Before the division, the entries of wordarray['chen'] are as follows:

[[2. 3.]
 [4. 1.]]

After the division by 10 (or 10.0) I get this for the same array:

[[1.01000000e-04   1.20000000e-05]
[1.11001000e-01   1.00000000e-06]]

Which doesn't seem to make any sense. I recognize that the double for-loops aren't that pythonic but this was what I thought to try when iterating with np.nditer didn't work. To address some of the comments, I did try dividing by both 10 and 10.0. The outcome was the same.

Also, when I perform the same operation without replacing the entries of the array and just print the division, i.e.:

for  word in allwords:
  for x in xrange(wordarrays[word].shape[0]):
     for y in xrange(wordarrays[word].shape[1]):
            print wordarrays[word][x][y]/10

I get what is expected, namely:

[[0.2 0.3]
 [0.4 0.1]]

Upvotes: 1

Views: 458

Answers (2)

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 59005

You can significantly improve your performance doing this:

for word in allwords:
    wordarrays[word] /= 10.

Upvotes: 4

BeRecursive
BeRecursive

Reputation: 6376

I assume it's because you are dividing by an Integer and so Integer arithmetic is being performed. Try changing 10 to 10.0.

e.g

for word in allwords:
    for x in xrange(wordarrays[word].shape[0]):
        for y in xrange(wordarrays[word].shape[1]):
            wordarrays[word][x][y]=wordarrays[word][x][y] / 10.0

Upvotes: 1

Related Questions