简体   繁体   中英

Issue in numpy when change numpy array value during vector normalization

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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM