简体   繁体   English

python numpy矢量数学

[英]python numpy vector math

What is the numpy equivalent to euclid 's 2d vector classes / operations ? numpyeuclid的2d向量类/运算等效吗? ( like: euclid.Vector2 ) (例如: 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. 您可以只使用numpy数组。 Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays wrt matrices. 查看numpy for matlab用户页面,详细了解数组wrt矩阵的优缺点。

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. 正如我在评论中提到的那样,必须使用dot()函数或方法对向量进行多重复制是最大的陷阱。 But then again, numpy arrays are consistent . 但话又说回来,numpy数组是一致的 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 . Edit2:ppe 465开始,从Python 3.5和numpy 1.10开始,您可以使用@ infix-operator进行矩阵乘法。

Edit: Regarding your comment: 编辑:关于您的评论:

  1. Yes. 是。 The whole of numpy is based on arrays. 整个numpy基于数组。

  2. Yes. 是。 linalg.norm(v) is a good way to get the length of a vector. linalg.norm(v)是获取向量长度的好方法。 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). 要标准化向量,只需将其除以您在(2)中计算的长度即可。 Division of arrays by a scalar is also element-wise. 标量对数组的分割也是按元素划分的。

    An example in ipython: 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 [5]是计算长度的另一种方法。 In [6] shows normalizing the vector. In [6]显示了归一化向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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