Check if the equation is linear for a specific set of variables

I have a script that automatically generates equations.

Equations are constructed using simplex symbols.

I would like to know if this is really a way to check if the equations are linear in terms of certain variables.

eg.

a, b, c, d = sympy.symbols('a, b, c, d') eq1 = c*b*a + b*a + a + c*d 

check the following: eq1 linear in terms of a , d ?

 True 
+6
source share
3 answers

A function is (jointly) linear in a given set of variables if all second-order derivatives are identically equal to zero (including mixed ones). This can be verified as follows:

 def is_linear(expr, vars): for x in vars: for y in vars: try: if not sympy.Eq(sympy.diff(expr, x, y), 0): return False except TypeError: return False return True 

In the cycle, each derivative is taken and checked for equality to zero. If sympy cannot decide whether it is equal to zero (raising a TypeError), then it is not identically equal to zero.

Output:

 >>> is_linear(eq1, [a,d]) True >>> is_linear(eq1, [a,c]) False 

To verify a separate linearity (for example, separately in and separately in b), discard mixed partial derivatives:

 def is_separately_linear(expr, vars): for x in vars: try: if not sympy.Eq(sympy.diff(expr, x, x), 0): return False except TypeError: return False return True 

Output:

 >>> is_separately_linear(eq1, [a,d]) True >>> is_separately_linear(eq1, [a,c]) True 
+3
source

The simplest way would be to check the degree of expression as a polynomial in each variable.

 In [17]: eq1 = c*b*a + b*a + a + c*d In [18]: degree(eq1, a) Out[18]: 1 In [19]: degree(eq1, d) Out[19]: 1 

and the expression is linear if the degree of the polynomial is <= 1.

If you know that the expression is a polynomial in your variables, you can also just check the permissions that the variable contains.

 In [21]: [i for i in eq1.atoms(Pow) if i.base == a] Out[21]: [] In [22]: eq2 = b*a**2 + d + c In [23]: [i for i in eq2.atoms(Pow) if i.base == a] Out[23]: ⎡ 2⎤ ⎣a ⎦ 
+3
source

To expand the answer from 404, if f xy = 0, then f yx = 0. Thus, the calculation time can be cut in half to solve mixed derivatives.

 from itertools import combinations_with_replacement def is_linear(expr, variables): combs = combinations_with_replacement(variables, 2) try: return all(sympy.Eq(sympy.diff(expr, *t), 0) for t in combs) except TypeError: return False 
+2
source

All Articles