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?
not a
sympy
expert, but given the limited accuracy offloat
, sympy can't be sure0.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)with the result
but as soon as you have any
floats
in your equation, you will likely getfloats
back. also in plain python:2 * 0.5 -> 1.0
.just tried: this also works: