python - Sympy - Comparing expressions -
is there way check if 2 expressions mathematically equal? expected tg(x)cos(x) == sin(x)
output true
, outputs false
. there way make such comparisons sympy? example (a+b)**2 == a**2 + 2*a*b + b**2
surprisingly outputs false
.
i found similar questions, none covered exact problem.
==
represents exact structural equality testing. “exact” here means 2 expressions compare equal == if equal structurally. here, (x+1)^2 , x^2+2x+1 not same symbolically. 1 power of addition of 2 terms, , other addition of 3 terms.it turns out when using sympy library, having
==
test exact symbolic equality far more useful having represent symbolic equality, or having test mathematical equality. however, new user, care more latter two. have seen alternative representing equalities symbolically, eq. test if 2 things equal, best recall basic fact if a=b, a−b=0. thus, best way check if a=b take a−b , simplify it, , see if goes 0. learn later function calledsimplify
. method not infallible—in fact, can theoretically proven impossible determine if 2 symbolic expressions identically equal in general—but common expressions, works quite well.
as demo particular question, can use subtraction of equivalent expressions , compare 0
>>> sympy import simplify >>> 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
Comments
Post a Comment