SymPy简化不能2 * 3 ** n / 3-> 2 * 3 **(n-1)

时间:2018-11-26 12:44:42

标签: sympy

在此先感谢您,英语不好!

FullScript.py

from sympy import *
var('n')
f= 3**n/3
print(simplify(f))
#---------------------
f= 2*3**n/3
print(simplify(f))
# 3**(n - 1) # OK
# 2*3**n/3   # I want  2*3**(n-1)

2018-11-27 ------------------------------

请告诉我如何使用if语句

How to extract numerator and denominator from polynomial without evaluating?

FullScript.py

from sympy import *
var('n')
def MySimplify(h):
    Mypoly = poly(h)
    aa = Mypoly.all_coeffs()[1]
    bb = h - aa
    n, d = fraction(bb)
    nn0 = n.as_base_exp()[0]
    nn1 = poly(nn0)
    import re
    rese1 = re.search('^Poly\((.+?),(.+?),', str(nn1)).group(1)
    rese2 = re.search('^Poly\((.+?),(.+?),', str(nn1)).group(2)
    two=sympify(rese1)/sympify(rese2)
    ans = powsimp(bb/two)*two+aa
    return ans

f= 3**n/3
print("f1=",f)
print("f2=",simplify(f))
g= 4+2*3**n/3
print("g1=",g)
print("g2=",simplify(g))
print("g3=",MySimplify(g))
# f1= 3**n/3
# f2= 3**(n - 1)
# g1= 2*3**n/3 + 4
# g2= 2*3**n/3 + 4
# g3= 2*3**(n - 1) + 4

2018-11-28 ------------------------------

FullScript.py

from sympy import *
var('m n p q r s t u v x')
def ps(e, *args):
 x = Dummy(integer=True)
 t=list(Add.make_args(e))
 for i, ti in enumerate(t):
  c, r = ti.as_coeff_Mul()
  if c.is_Rational and not c.is_Integer:
    t[i] = Mul(c.p, r, Pow(c.q, x), evaluate=False)
    # t[i] = powersimp(t[i], *args).xreplace({x: -1})
    t[i] = powsimp(t[i], *args).xreplace({x: -1})
  else:
    t[i] = powsimp(t[i], *args)
 return Add(*t)

f= 4+2*3**n/3
print("f1=",f)
print("f1=",ps(f))
f= 4+2*3**n/3+5*2.4**(m-1)/2.4+6*5.6*(p-7)/8.9
print("f2=",f)
print("f2=",ps(f))
g= x+p**n/p
print("g1=",g)
print("g1=",ps(g))
g= x+p**n/p+q*s**(m-1)/s+r*t**(u-2)/v
print("g2=",g)
print("g2=",ps(g))

# f1= 2*3**n/3 + 4
# f1= 2*3**(n - 1) + 4

# f2= 2.08333333333333*2.4**(m - 1) + 2*3**n/3     + 3.7752808988764*p - 22.4269662921348
# f2= 2.08333333333333*2.4**(m - 1) + 2*3**(n - 1) + 3.7752808988764*p - 22.4269662921348

# g1= x + p**n/p
# g1= p**(n - 1) + x

# g2= q*s**(m - 1)/s + r*t**(u - 2)/v + x + p**n/p
# g2= p**(n - 1) + q*s**(m - 2) + r*t**(u - 2)/v + x

1 个答案:

答案 0 :(得分:1)

powsimp(f/2)*2将做您想要的。以下是结合了此想法的更通用的解决方法:

def ps(e, *args):
 x = Dummy(integer=True)
 t=list(Add.make_args(e))
 for i, ti in enumerate(t):
  c, r = ti.as_coeff_Mul()
  if c.is_Rational and not c.is_Integer:
    t[i] = Mul(c.p, r, Pow(c.q, x), evaluate=False)
    t[i] = powersimp(t[i], *args).xreplace({x: -1})
  else:
    t[i] = powsimp(t[i], *args)
 return Add(*t)