SymPy 基础知识
我刚刚开始玩 SymPy 我对它的一些行为感到有点惊讶,例如这不是我期望的结果:
>>> import sympy as s
>>> (-1)**s.I == s.E**(-1* s.pi)
False
>>> s.I**s.I == s.exp(-s.pi/2)
False
为什么这些返回 False 并且有办法吗让它从一种写复数的方式转换为另一种写复数的方式?
I am just starting to play with SymPy and I am a bit surprised by some of its behavior, for instance this is not the results I would expect:
>>> import sympy as s
>>> (-1)**s.I == s.E**(-1* s.pi)
False
>>> s.I**s.I == s.exp(-s.pi/2)
False
Why are these returning False and is there a way to get it to convert from one way of writing a complex number to another?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 常见问题:
为什么 SymPy 说两个相等表达式不相等?
相等运算符 (==) 测试表达式是否具有相同的形式,而不是它们在数学上是否相等。
为了使相等测试在基本情况下有用,SymPy 在评估它们时尝试将数学上等效的表达式重写为规范形式。例如,SymPy 将 x+x 和 -(-2*x) 计算为 2*x,将 x*x 计算为 x**2。
默认变换无法生成规范形式的最简单示例是非线性多项式,它可以以因式分解和展开形式表示。尽管在数学上显然是
a(1+b) = a+ab
,但 SymPy 给出:同样,SymPy 无法检测到差异为零:
如果您想确定非平凡表达式的数学等价性,您应该对方程两边应用更高级的简化例程。对于多项式,可以通过完全展开表达式来将其重写为规范形式。这是使用 SymPy 中的
.expand()
方法完成的:如果
.expand()
没有帮助,请尝试simplify()
,trigsimp()
等,尝试更高级的转换。例如,From the FAQ:
Why does SymPy say that two equal expressions are unequal?
The equality operator (==) tests whether expressions have identical form, not whether they are mathematically equivalent.
To make equality testing useful in basic cases, SymPy tries to rewrite mathematically equivalent expressions to a canonical form when evaluating them. For example, SymPy evaluates both x+x and -(-2*x) to 2*x, and x*x to x**2.
The simplest example where the default transformations fail to generate a canonical form is for nonlinear polynomials, which can be represented in both factored and expanded form. Although clearly
a(1+b) = a+ab
mathematically, SymPy gives:Likewise, SymPy fails to detect that the difference is zero:
If you want to determine the mathematical equivalence of nontrivial expressions, you should apply a more advanced simplification routine to both sides of the equation. In the case of polynomials, expressions can be rewritten in a canonical form by expanding them fully. This is done using the
.expand()
method in SymPy:If
.expand()
does not help, trysimplify()
,trigsimp()
, etc, which attempt more advanced transformations. For example,因为他们不平等。试试这个:
sE**(sI* s.pi)== sI*sI
Because they're not equal. Try this one:
s.E**(s.I* s.pi)== s.I*s.I