简体   繁体   English

有没有办法使用 Sympy 扩展多项式?

[英]Is there a way to expand polynomials using Sympy?

Looking at the Sympy documentation, there seems to be an "expand" function which can be called upon to expand polynomial expressions;查看 Sympy 文档,似乎有一个“扩展” function 可以调用它来扩展多项式表达式; however, in practice, this is not working for me.但是,在实践中,这对我不起作用。 I started off using imaginary numbers:我开始使用虚数:

import sympy
sympy.expand((x - 1)(x + i)(x - i))

Hoping for "x^3 - x^2 + x - 1", however, instead, this returned the following error: module 'sympy' has no attribute 'expand'希望“x^3 - x^2 + x - 1”,然而,这却返回了以下错误:模块'sympy'没有属性'expand'

I then changed the expression I wanted to be expanded, as this had caused me to assume that Sympy could not handle complex numbers, to what can be seen below:然后我更改了我想要扩展的表达式,因为这使我假设 Sympy 无法处理复数,如下所示:

import sympy
sympy.expand((x - 1)(x - 1)(x + 1))

Yet this returned the same error.然而,这返回了同样的错误。

The imaginary i is represented by the capital I in sympy.虚构的i由 sympy 中的大写字母I表示。 To have a multiplication, an * needs to be used explicitly.要进行乘法运算,需要显式使用* Also, in Python ^ is strictly reserved for a boolean (or bitwise) exclusive or.此外,在 Python 中, ^严格保留用于 boolean(或按位)异或。 Power is represented as ** .功率表示为**

from sympy import symbols, I, expand

x = symbols('x') 
print(expand((x - 1)*(x + I)*(x - I)))

Output: x**3 - x**2 + x - 1 Output: x**3 - x**2 + x - 1

Note that an alternative way to call expand() is as expression.expand() (or ((x - 1)*(x + I)*(x - I)).expand() as in the example).请注意,调用expand()的另一种方法是expression.expand() (或((x - 1)*(x + I)*(x - I)).expand() ,如示例中所示)。 Often this is a handy way to concatenate several operations.通常这是连接多个操作的便捷方式。

I don't have problem to run我没有问题运行

import sympy

x = sympy.Symbol('x')
i = sympy.Symbol('i')

sympy.expand( (x - 1)*(x + i)*(x - i) )

and this gives me这给了我

-i**2*x + i**2 + x**3 - x**2

The only idea: you created file with name sympy.py and now import sympy loads your file instead of module sympy and it can't find expand in your file.唯一的想法:您创建了名为sympy.py的文件,现在import sympy加载您的文件而不是模块sympy并且它在您的文件中找不到expand You have to rename your file sympy.py to something different (which is not name of other module).您必须将文件sympy.py重命名为不同的名称(不是其他模块的名称)。

But you didn't add full error message in question so I can't confirm it.但是您没有添加完整的错误消息,所以我无法确认。

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

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