简体   繁体   中英

python numpy vector math

What is the numpy equivalent to euclid 's 2d vector classes / operations ? ( like: euclid.Vector2 )

So far I have this. Create two vectors

import numpy as np

loc = np.array([100., 100.])
vel = np.array([30., 10])

loc += vel

# reseting speed to a default value, maintaining direction
vel.normalize()
vel *= 200

loc += vel

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays wrt matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent . All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465 .

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

     In [1]: import math In [2]: import numpy as np In [3]: a = np.array([4,2,7]) In [4]: np.linalg.norm(a) Out[4]: 8.3066238629180749 In [5]: math.sqrt(sum([n**2 for n in a])) Out[5]: 8.306623862918075 In [6]: b = a/np.linalg.norm(a) In [7]: np.linalg.norm(b) Out[7]: 1.0 

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

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