Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify logarithm of exponent in sympy?

When I type

import sympy as sp
x = sp.Symbol('x')
sp.simplify(sp.log(sp.exp(x)))

I obtain

log(e^x)

Instead of x. I know that "there are no guarantees" on this function.

Question. Is there some specific simplification (through series expansion or whatsoever) to convert logarithm of exponent into identity function?

like image 935
Sergey Dovgal Avatar asked Sep 09 '17 09:09

Sergey Dovgal


People also ask

How do you use log in SymPy?

With the help of sympy. log() function, we can simplify the principal branch of the natural logarithm. Logarithms are taken with the natural base, e. To get a logarithm of a different base b, use log(x, y), which is essentially short-hand for log(x) / log(y).

How do you simplify algebraic expressions in Python?

simplify() method, we can simplify any mathematical expression. Parameters: expression – It is the mathematical expression which needs to be simplified. Returns: Returns a simplified mathematical expression corresponding to the input expression.

How do you write an ex in SymPy?

Note that by default in SymPy the base of the natural logarithm is E (capital E ). That is, exp(x) is the same as E**x .


2 Answers

You have to set x to real type and your code will work:

import sympy as sp
x = sp.Symbol('x', real=True)
print(sp.simplify(sp.log(sp.exp(x))))

Output: x.

For complex x result of this formula is not always is equal to x. Example is here.

like image 82
Serenity Avatar answered Oct 04 '22 00:10

Serenity


If you want to force the simplification, expand can help because it offers the force keyword which basically makes certain assumptions like this for you without you having to declare your variables as real. But be careful with the result -- you will not want to use it when those assumptions are not warranted.

>>> log(exp(x)).expand(force=True)
x
like image 42
smichr Avatar answered Oct 03 '22 23:10

smichr