Pillsy
Pillsy

Reputation: 9901

Using diff on a SymPy Function object returns 1

I set up an undefined function and a variable to go with it:

import sympy as sp

f = sp.Function('f')
t = sp.Symbol('t')

If I differentiate f(t) with respect to t, it works fine:

f(t).diff(t)
# Derivative(f(t), t)

However, if I differentiate f itself with respect to t, I get this:

f.diff(t)
# 1

I'm not exactly sure what I expected here (probably an error), but I certainly didn't expect 1. What's going on?

Upvotes: 0

Views: 106

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14480

A SymPy Function object is actually a Python class:

In [15]: f = Function('f')

In [16]: type(f(t))
Out[16]: f

In [17]: isinstance(f(t), f)
Out[17]: True

This is analogous to cos(t) being an instance of the cos class. Consequently f.diff is equivalent to Expr.diff i.e. an unbound class method:

In [18]: f.diff
Out[18]: <function sympy.core.expr.Expr.diff(self, *symbols, **assumptions)>

In [19]: Expr.diff
Out[19]: <function sympy.core.expr.Expr.diff(self, *symbols, **assumptions)>

In [20]: Expr.diff(t)
Out[20]: 1

This is equivalent to:

In [21]: t.diff()
Out[21]: 1

Note that the diff method allows not specifying the differentiation variable if the expression only has one symbol:

In [22]: sin(t).diff(t)
Out[22]: cos(t)

In [23]: sin(t).diff()
Out[23]: cos(t)

Upvotes: 1

Related Questions