Michael Yuxi Dong Michael Yuxi Dong - 1 year ago 206
Python Question

How does sympy simplify ln((exp(x)+1)/exp(x)) to log(1+exp(-x))?

If I use

function in sympy,
does simplify to
, however, as I read the doc, the simplify function is "can be unnecessarily slow", I tried other simplification methods, but non of them works, so I'm wondering how do I simplify
to the form like this
without calling simplify().

Answer Source

You can more directly just use sympy.polys.polytools.cancel(), which is available as a method on your expression with .cancel().

>>> from sympy.abc import x
>>> from sympy import *
>>> my_expr = log((exp(x)+1)/exp(x))
>>> my_expr.cancel()
log(1 + exp(-x))

This is what is doing the work of simplifying your expression inside simplify().

A very naive benchmark:

>>> import timeit
>>> %timeit my_expr.simplify()
100 loops, best of 3: 7.78 ms per loop
>>> %timeit my_expr.cancel()
1000 loops, best of 3: 972 ┬Ás per loop
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download