Python – The sympy parser does not recognize expm1 as a symbolic function

The sympy parser does not recognize expm1 as a symbolic function… here is a solution to the problem.

The sympy parser does not recognize expm1 as a symbolic function

The function expm1 is not parsed correctly in the following example:

from sympy.parsing.sympy_parser import parse_expr
print parse_expr('expm1(x)').diff('x')

Giving

Derivative(expm1(x), x)

How to get Sympy to recognize expm1 as a symbolic function in order to get

the same result as

print parse_expr('exp(x) - 1').diff('x')

It gives exp(x)?

Solution

Since there is no built-in expm1 in SymPy, the parser knows nothing about this notation. parse_expr arguments local_dict can be used to explain to SymPy the meaning of unfamiliar functions and symbols.

expm1 = lambda x: exp(x)-1
parse_expr('expm1(x)', local_dict={"expm1": expm1})

This returns exp(x) - 1.

To keep expm1 as a single function with a known derivative instead of exp(x)-1, define it as a SymPy function (see for more such examples tutorial)。

class expm1(Function):
    def fdiff(self, argindex=1):
        return exp(self.args[0])

Confirm that this works:

e = parse_expr('expm1(x)', local_dict={"expm1": expm1})
print(e)           # expm1(x)
print(e.diff(x))   # exp(x)
f = lambdify(x, e)
print(f(1))        # 1.718281828459045
print(f(1e-20))    # 1e-20, unlike exp(x)-1 which would evaluate to 0

Related Problems and Solutions