Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SymPy, simplification / substitution using known patterns or sub-expressions

I have the following expression:

from sympy import pi, sin, cos, var, simplify
var('j,u,v,w,vt,wt,a2,t,phi')

u0 = v*a2*sin(pi*j/2 + pi*j*t*phi**(-1)/2) + pi*vt*a2*cos(pi*j/2 + pi*j*t*phi**(-1)/2)*j*phi**(-1)/2 + pi*w*a2*cos(pi*j/2 + pi*j*t*phi**(-1)/2)*j*phi**(-1)

Which can be simplified:

print simplify(u0)
#a2*(pi*j*vt*cos(pi*j*(phi + t)/(2*phi)) + 2*pi*j*w*cos(pi*j*(phi + t)/(2*phi)) + 2*phi*v*sin(pi*j*(phi + t)/(2*phi)))/(2*phi)

Given the sub-expressions:

bj = pi*j*(phi + t)/(2*phi)
cj = j*pi/(2*phi)

Currently I substitute manually bj and cj in the simplified u0 expression to get:

u0 = a2*(v*sin(bj) + cj*vt*cos(bj) + 2*cj*w*cos(bj))

Is it possible to use SymPy to achieve that, avoiding the manual substitution?

like image 956
Saullo G. P. Castro Avatar asked Aug 02 '13 07:08

Saullo G. P. Castro


People also ask

How can I substitute SymPy?

The subs() function in SymPy replaces all occurrences of first parameter with second. This function is useful if we want to evaluate a certain expression. For example, we want to calculate values of following expression by substituting a with 5.

How do you evaluate a SymPy expression?

To evaluate a numerical expression into a floating point number, use evalf . SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf .

How do you simplify equations in Python?

simplify() method, we can simplify any mathematical expression. Parameters: expression – It is the mathematical expression which needs to be simplified. Returns: Returns a simplified mathematical expression corresponding to the input expression.

How do you substitute a value in a function Python?

With the help of sympy. subs() method, we can substitute all instances of a variable or expression in a mathematical expression with some other variable or expression or value. Parameters: variable – It is the variable or expression which will be substituted.


2 Answers

I guess what you are missing is that subs will replace arbitrary expressions, not just symbols

>>> print simplify(u0).subs({pi*j*(phi + t)/(2*phi): bj, j*pi/(2*phi): cj})
a2*(pi*j*vt*cos(bj) + 2*pi*j*w*cos(bj) + 2*phi*v*sin(bj))/(2*phi)

(I used simplify because that is what results in the pi*j*(phi + t)/(2*phi) instead of pi*j/2 + pi*j*t/(2*phi), but it's not otherwise required)

Read http://docs.sympy.org/0.7.3/tutorial/basic_operations.html#substitution for more information about substitution and replacement. If you want to do more advanced replacement, take a look at the replace method.

like image 170
asmeurer Avatar answered Oct 17 '22 08:10

asmeurer


You can find common subexpressions with the cse routine.

like image 45
Krastanov Avatar answered Oct 17 '22 06:10

Krastanov