qoder
qoder

Reputation: 13

How to simplify the expression using sympy?

How can this expression

4x^3 + 16x^2 + 24x + 8 = 4y^2 + 2y + 8

be reduced to

2x^3 + 8x^2 + 12x + 4 = 2y^2 + y + 4

using sympy?

The expression is given as a string:

input_string = "45x^3 + 39x^2 + 24x + 9 = 4y^2 + 2y + 8" 

Upvotes: 1

Views: 107

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14530

First step is to parse the string into a SymPy expression:

In [51]: from sympy import parse_expr

In [52]: input_string = "4x^3 + 16x^2 + 24x + 8 = 4y^2 + 2y + 8"

In [53]: eq = parse_expr(input_string, transformations="all")

In [54]: eq
Out[54]: 
   3       2                 2          
4⋅x  + 16⋅x  + 24⋅x + 8 = 4⋅y  + 2⋅y + 8

Now I presume what you want is just to divide both sides by the gcd of their coefficients so get all the coefficients and compute their gcd:

In [55]: coeffs = Poly(eq.lhs).coeffs() + Poly(eq.rhs).coeffs()

In [56]: coeffs
Out[56]: [4, 16, 24, 8, 4, 2, 8]

In [57]: g = gcd(coeffs)

In [58]: g
Out[58]: 2

In [59]: neweq = Eq(eq.lhs/g, eq.rhs/g)

In [60]: neweq
Out[60]: 
   3      2                 2        
2⋅x  + 8⋅x  + 12⋅x + 4 = 2⋅y  + y + 4

Upvotes: 1

Related Questions