python numpy矢量数学 [英] python numpy vector math

查看:87
本文介绍了python numpy矢量数学的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

euclid 的2d向量类/操作等效的numpy是什么? ? (例如:euclid.Vector2)

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

推荐答案

您可以只使用numpy数组.查看面向MATLAB用户的numpy 页,数组优缺点的详细概述矩阵.

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 w.r.t. matrices.

正如我在评论中提到的那样,必须使用dot()函数或方法对载体进行多重复制是最大的陷阱.但是话又说回来,numpy数组是一致的.所有操作都是按元素进行的.因此,对数组进行加法或减法以及与标量的乘法都可以按向量的预期进行工作.

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 :从Python 3.5和numpy 1.10开始,由于

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

关于您的评论:

  1. 是的.整个numpy都是基于数组的.

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

是的. linalg.norm(v)是获取向量长度的好方法.但是,您所得到的取决于对规范的第二个论点!阅读文档.

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.

要归一化向量,只需将其除以您在(2)中计算的长度即可.标量对数组的分割也是按元素划分的.

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

ipython中的示例:

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

请注意,In [5]是计算长度的另一种方法. In [6]显示归一化向量.

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

这篇关于python numpy矢量数学的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆