pythonsympy

Convert log(x)/log(2) to log_2(x) in sympy


I received a sympy equation from a library. It makes extensive use of log2, but the output was converted to log(x)/log(2). This makes reading the results messy.

I would like to have sympy simplify this equation again with a focus on using log2 directly where possible.

How could this be done?

Example:

(log(A) / log(2)) * (log(B + C) / log(2))

Solution

  • Basically, you can just reverse the process: replace log(w) with log(2) * log2(w) and let sympy cancel all the factors of log(2) / log(2).

    The only wrinkle is that you don't want to substitute when you find log(2) itself, but that's easy enough. You just use a wildcard, and check if the matched value is literally 2 before doing the substitution:

    import sympy
    from sympy import log
    from sympy.codegen.cfunctions import log2
    A, B, C = sympy.symbols("A, B, C")
    w = sympy.Wild("w")
    expr = (log(A) / log(2)) * (log(B + C) / log(2))
    expr.replace(log(w), lambda w: log(2) if w==2 else log(2)*log2(w))
    

    The result is

    log2(A)*log2(B + C)
    

    which is correct.

    [H/T @ThomasWeller for finding log2 buried in codegen.]