Vincent mahé
Vincent mahé

Reputation: 51

Sympy does not recognize that the real part of the derivative of a real function is real

I want to evaluate Re(df(t)/dt) where t is real and f(t) is real. However, this does not work using sympy. Here is a example:

from sympy import re, im, symbols, Function

t = symbols('t',real=True)
f = Function('f',real=True)(t)

print(re(f))
print(re(t))
print(re(f.diff(t)))

This will print

f(t)
t
re(Derivative(f(t), t))

The two first prints are as expected, but I expected the last one to be

Derivative(f(t), t)

I checked the issue "simplify does not simplify complex numbers composed into real and imaginary part #18271" which led me to try (f.diff(t)).expand(complex=True,deep=True) and (f.diff(t)).as_real_imag(), but it still does not recognize that df(t)/dt is real.

I also looked at what re and im do (source code is here https://henrikfinsberg.com/docs.gotran/_modules/sympy/functions/elementary/complexes.html) but I don't understand it well enough to find a way out.

Would you know how to solve this issue or have a workaround? Thanks!

Upvotes: 1

Views: 464

Answers (1)

smichr
smichr

Reputation: 19057

I would just do a replacement:

>>> re(f.diff(t)).replace(lambda x: isinstance(x, re) and
...                           x.args[0].is_Derivative
...                           and x.args[0].expr.is_real,
...                       lambda x: x.args[0])
Derivative(f(t), t)

Upvotes: 1

Related Questions