Sympy - 比较表达式 [英] Sympy - Comparing expressions

查看:32
本文介绍了Sympy - 比较表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检查两个表达式在数学上是否相等?我期望tg(x)cos(x) == sin(x) 输出True,但输出False.有没有办法与 sympy 进行这样的比较?另一个例子是(a+b)**2 == a**2 + 2*a*b + b**2 令人惊讶的是它也输出 False.

我发现了一些类似的问题,但没有一个涵盖这个确切的问题.

解决方案

来自 SymPy 文档

<块引用>

== 表示精确的结构相等性测试.这里的精确"意味着两个表达式只有在结构上完全相等时才会与 == 进行比较.这里,(x+1)^2 和 x^2+2x+1 在符号上并不相同.一个是两个项相加的幂,另一个是三个项相加的幂.

事实证明,当使用 SymPy 作为库时,使用 == 测试精确符号相等比让它表示符号相等或测试数学相等要有用得多.但是,作为新用户,您可能会更关心后两者.我们已经看到了一个替代的符号表示等式,方程.要测试两件事是否相等,最好回忆一个基本事实,即如果 a=b,则 a−b=0.因此,检查是否 a=b 的最佳方法是取 a−b 并简化它,看看它是否为 0.我们稍后将了解到执行此操作的函数称为 simplify.这种方法并非万无一失——事实上,理论上可以证明,一般情况下无法确定两个符号表达式是否完全相同——但对于大多数常见表达式来说,它效果很好.

作为您特定问题的演示,我们可以使用等效表达式的减法并像这样与 0 进行比较

<预><代码>>>>from sympy import 简化>>>从 sympy.abc 导入 x,y>>>vers1 = (x+y)**2>>>vers2 = x**2 + 2*x*y + y**2>>>简化(vers1-vers2)== 0真的>>>简化(vers1+vers2) == 0错误的

Is there a way to check if two expressions are mathematically equal? I expected tg(x)cos(x) == sin(x) to output True, but it outputs False. Is there a way to make such comparisons with sympy? Another example is (a+b)**2 == a**2 + 2*a*b + b**2 which surprisingly also outputs False.

I found some similar questions, but none covered this exact problem.

解决方案

From the SymPy documentation

== represents exact structural equality testing. "Exact" here means that two expressions will compare equal with == only if they are exactly equal structurally. Here, (x+1)^2 and x^2+2x+1 are not the same symbolically. One is the power of an addition of two terms, and the other is the addition of three terms.

It turns out that when using SymPy as a library, having == test for exact symbolic equality is far more useful than having it represent symbolic equality, or having it test for mathematical equality. However, as a new user, you will probably care more about the latter two. We have already seen an alternative to representing equalities symbolically, Eq. To test if two things are equal, it is best to recall the basic fact that if a=b, then a−b=0. Thus, the best way to check if a=b is to take a−b and simplify it, and see if it goes to 0. We will learn later that the function to do this is called simplify. This method is not infallible—in fact, it can be theoretically proven that it is impossible to determine if two symbolic expressions are identically equal in general—but for most common expressions, it works quite well.

As a demo for your particular question, we can use the subtraction of equivalent expressions and compare to 0 like so

>>> from sympy import simplify
>>> from sympy.abc import x,y
>>> vers1 = (x+y)**2
>>> vers2 = x**2 + 2*x*y + y**2
>>> simplify(vers1-vers2) == 0
True
>>> simplify(vers1+vers2) == 0
False

这篇关于Sympy - 比较表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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