简体   繁体   English

在sympy中计算向量的x分量

[英]compute x-component of vector in sympy

I'm sure this is a really basic question, but I've googled and haven't found it. 我确信这是一个非常基本的问题,但我用Google搜索并没有找到它。 Supposed I have a vector in sympy 假设我有一个同情的载体

z = 3*x + 4*y

How do I compute the x-component of the vector (ie the 3)? 如何计算向量的x分量(即3)? z/x doesn't give it (there's still the y-part), nor does z[x] or zx Surely there's a way to do this, right? z / x没有给它(仍然是y部分),z [x]或zx也没有确实有办法做到这一点,对吧?

Is it as simple as: 它是如此简单:

>>> from sympy.abc import x, y
>>> z = 3*x + 4*y
>>> z.coeff(x)
3

I think that calling this expression a vector is somewhat incorrect. 我认为将这个表达式称为向量有点不正确。 Indeed, if you keep in your mind the assumption that x and y are some base vectors, it will work in your mind . 实际上,如果你在脑海中假设xy是一些基本向量,它将在你的脑海中起作用。 However the library will not provide any vector-like functionality because it does not know that you want to treat this as vectors. 但是,库不会提供任何类似矢量的功能,因为它不知道您希望将其视为矢量。

For vector with all the nice helper methods you can use the diffgeom submodule of sympy which provides predefined R^2 and R^3 spaces with numerous coordinate systems. 对于具有所有漂亮辅助方法的向量,您可以使用diffgeom子模块,该子模块提供具有多个坐标系的预定义R^2R^3空间。

However, for your case pattern matching seems a much more natural choice. 但是,对于您的案例, 模式匹配似乎是一个更自然的选择。 After all pattern matching is one of the basic building blocks of CASes like Mathematica and others. 所有模式匹配都是像Mathematica等其他CAS的基本构建块之一。

In SymPy as in all other CASes you work with symbolic expressions which are basically big trees with operators at each node and some symbols at the leafs. 在SymPy和所有其他CAS中一样,您使用符号表达式,这些符号表达式基本上是大树,每个节点都有运算符,叶子处有一些符号。 You can match trees against some predefined patterns much in the same way in which you can use regex on strings. 您可以将树与某些预定义模式匹配,就像在字符串上使用正则表达式一样。 In sympy you use Wild to do that: 同情你使用Wild来做到这一点:

x, y = Symbols("x y")
a, b = Wild('a', exclude=[x, y]), Wild('b', exclude=[x, y])
(2*x + 3*y).match(a*x + b*y)

For the special case of linear combinations check coeff which is described in the other answer. 对于线性组合的特殊情况,检查coeff ,在另一个答案中描述。

See: https://github.com/sympy/sympy/wiki/Idioms-and-Antipatterns#wild-and-match 请参阅: https//github.com/sympy/sympy/wiki/Idioms-and-Antipatterns#wild-and-match

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

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