1

Say I have a numpy array a = np.array([[1,2,3],[2,3,4]])

I want make this two vectors into unit vectors. The working code is

for i in range(2):
    a[i] = a[i]/np.linalg.norm(a[i])

In the end, the result a become:

a =

array([[0, 0, 0],
       [0, 0, 0]])

while if I run the calculation and print out the results like

for i in range(2):
    print(a[i],i,np.linalg.norm(a[i]))

The code would print out correct results as unit vectors.

Hence my question are : 1. Why the numpy array become zero if I assign it to the unit vector results. 2. what is the correct way to change a list of vectors into unit vectors by numpy array?

Thank you all very much!

1
  • 2
    a is int dtype. values are truncated. Commented May 8, 2021 at 8:43

1 Answer 1

1

Because numpy.array() requires you to declare the data type of objects contained in the array. If not declared it will be determined as the minimum data type. In your case it will be an int. To solve your problem you can either make a new array with dtype = float or declare a's dtype.

a = np.array([[1,2,3],[2,3,4]], dtype=np.float32)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the clarification. Must numpy declare the data type at the start of the assignment? Can I change the dtype some where later?
no, you can change it later using .astype()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.