Simple symbolic algebra rearranging with Sympy can't preserve logarithms symbolically

534 Views Asked by At

I'm trying to use Sympy to rearrange simple expressions; although it seems that Sympy refuses to keep the result as a symbolic expression, and instead evaluates the logarithm numerically.

Is there a way to force Sympy to return the result symbolically?

Here is a minimum working example:

import sympy as sy

sy.init_printing()

def rearrange(expression, lhs):
    rhs = sy.solve(expression,lhs)[0]
    return sy.Eq(lhs, rhs)

a, b = sy.symbols('a, b', real=True, positive=True)

eqn = sy.Eq(sy.exp(-a**2/b**2), 0.5)

rearrange(eqn, a)

which returns

a=0.832554611157698b

This is the correct answer of course, although I would have preferred to be told the symbolic algebra result, which (when derived manually) is:

a = sqrt(log(2)) * b

where log is base e (i.e. natural log, ln).

How can I obtain this result from Sympy please?

1

There are 1 best solutions below

0
On BEST ANSWER

not a sympy expert, but given the limited accuracy of float, sympy can't be sure 0.5 == 1/2. i rearranged the equation a bit so only integers come into play (Fractions or something similar will certainly also do the trick)

eqn = sy.Eq(2*sy.exp(-a**2/b**2), 1)

with the result

a == b*sqrt(log(2))

but as soon as you have any floats in your equation, you will likely get floats back. also in plain python: 2 * 0.5 -> 1.0.

just tried: this also works:

eqn = sy.Eq(sy.exp(-a**2/b**2), Fraction(1, 2))