0

I want to assign row-specific values to each row in a 2D numpy array. In particular, each row should contain the value of the reciprocal of its row number. In other words, all columns in row 1 should have values 1, all columns in row 2 should be 1/2, all in row 3 should be 1/3, and so on. I tried this:

m = 3
n = 10

train = np.empty([n,m], float)

for curr_n in range(n):
    train[curr_n,:] = 1/(curr_n+1)

print train

But the output is:

[[ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

What am I doing wrong? I used "float" at the beginning, but I'm still getting solid 0 integers for all but the first row.

3
  • 2
    you need 1. to convert it to a float. Commented Apr 21, 2014 at 12:19
  • np.true_divide Commented Apr 21, 2014 at 13:30
  • 1
    1/(curr_n+1) always return 1 or 0 because curr_n is a type of integer. You might want to do like 1.0/(curr_n+1) or 1/float(curr_n+1). Commented Apr 21, 2014 at 13:51

2 Answers 2

5

Implicit type conversion has been added in Python 3, so your original code will then work, as is:

from __future__ import division

m = 3
n = 10

train = np.empty([n,m], float)

for curr_n in range(n):
   train[curr_n,:] = 1/(curr_n+1)

print train

Some information on the __future__ module can be seen in the official docs future module

Or, as sshashank124 put in his answer and I put in the comment, you can use 1. or 1.0 to force float behavior.

Sign up to request clarification or add additional context in comments.

Comments

3

You have a simple type problem. Use 1.0 instead of 1 in your reciprocation. The following works:

m = 3
n = 10

train = np.empty([n,m])

for curr_n in range(n):
    train[curr_n,:] = 1.0/(curr_n+1)   #converted 1 to 1.0

print train

Explanation

Although you might think that numpy deals with floats by default, in this case, the numpy array is getting assigned the value after python has had the time to calculate the inverses. It is then that python truncates your floats to an int and numpy innocently converts that sneaky int to a float just as it is supposed to and ends up taking all the blame.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.