Given the formula, I want to convert it to a Poly object and minimize the size of the generator. For example, if my formula is x^2+x+sqrt(x)
, I would expect to have only sqrt(x)
in the generator. But in most of my attempts, the generator contains both x
and sqrt(x)
.
from sympy import *
print('first attempt:',Poly('x^2+x+sqrt(x)'))
x=Symbol('x', positive=True)
print('second attempt:',Poly(x**2+x+sqrt(x)))
print('third attempt:',str(Poly({1:1,2:1,4:1},gens=S('sqrt(x)'))))
first attempt: Poly(x**2 + x + (sqrt(x)), x, sqrt(x), domain='ZZ')
second attempt: Poly(x**2 + x + (sqrt(x)), x, sqrt(x), domain='ZZ')
third attempt: Poly((sqrt(x))**4 + (sqrt(x))**2 + (sqrt(x)), sqrt(x), domain='ZZ')
Only the third method was successful, but the code for it is ugly and hard to automatize (I want to convert it because I want to easily extract coefficients and powers, so it gives me nothing). Is there a nicer way to do it?
EDIT
Based on smichr response, I've created a function to reduce the size of the generator.
def _powr(formula):
if formula.func==Pow:
return formula.args
else:
return [formula,S('1')]
def reducegens(formula):
pol=Poly(formula)
newgens={}
ind={}
for gen in pol.gens:
base,pw=_powr(gen)
coef,_=pw.as_coeff_mul()
ml=pw/coef
if base**ml in newgens:
newgens[base**ml]=gcd(newgens[base**ml],coef)
else:
newgens[base**ml]=coef
ind[base**ml]=S('tmp'+str(len(ind)))
for gen in pol.gens:
base,pw=_powr(gen)
coef,_=pw.as_coeff_mul()
ml=pw/coef
pol=pol.replace(gen,ind[base**ml]**(coef/newgens[base**ml]))
newpol=Poly(pol.as_expr())
for gen in newgens:
newpol=newpol.replace(ind[gen],gen**newgens[gen])
return newpol
I've tried it on several examples and it's not bad, but there is room for improvements.
print(reducegens(S('x^2+x+sqrt(x)')))
print(reducegens(S('x**2+y**2+x**(1/2)+x**(1/3)')))
print(reducegens(S('sqrt(x)+sqrt(z)+sqrt(x)*sqrt(z)')))
print(reducegens(S('sqrt(2)+sqrt(3)+sqrt(6)')))
Poly((sqrt(x))**4 + (sqrt(x))**2 + (sqrt(x)), sqrt(x), domain='ZZ')
Poly((x**(1/6))**12 + (x**(1/6))**3 + (x**(1/6))**2 + y**2, x**(1/6), y, domain='ZZ')
Poly((sqrt(x))*(sqrt(z)) + (sqrt(x)) + (sqrt(z)), sqrt(x), sqrt(z), domain='ZZ')
Poly((sqrt(2)) + (sqrt(3)) + (sqrt(6)), sqrt(2), sqrt(3), sqrt(6), domain='ZZ')
There first three examples are OK, but it would be nice to represent sqrt(6) as sqrt(2)*sqrt(3) and not as another generator's element.