Search code examples
sympyexponentsimplification

sympy how to simplify expressions with a variable as exponent


I have an expression like this one: 4^k/(12^k*A+4^k*B)

Python code is:

import sympy as sy
k,A,B=sy.symbols('k A B',real=True)
C=sy.Rational(4)**k/(sy.Rational(12)**k*A+sy.Rational(4)**k*B)

Is there any SymPy function able to simplify the expression? Something like radcan in MAXIMA. I tried sy.simplify(C), sy.factor(C), sy.powsimp(C), sy.radsimp(C), sy.expand(C) without success.


Solution

  • We need to force the factorisation of the integers which we can do with factorint:

    In [46]: C                                                                                                                                                    
    Out[46]: 
          k     
         4      
    ────────────
      k      k  
    12 ⋅A + 4 ⋅B
    
    In [47]: C.replace(lambda x: x.is_Integer, lambda x: Mul(*factorint(x, multiple=True), evaluate=False))                                                       
    Out[47]: 
                 k       
            (2⋅2)        
    ─────────────────────
             k          k
    A⋅(2⋅2⋅3)  + B⋅(2⋅2) 
    
    In [48]: expand(_)                                                                                                                                            
    Out[48]: 
            2⋅k       
           2          
    ──────────────────
     2⋅k  k      2⋅k  
    2   ⋅3 ⋅A + 2   ⋅B
    
    In [49]: cancel(_)                                                                                                                                            
    Out[49]: 
       1    
    ────────
     k      
    3 ⋅A + B