TypeError: object is not callable when solving for 1st order ODEs?

26 Views Asked by At

This is the code I've written and been provided with, and below is the error I am repeatedly getting. I've tried using both y.diff & Derivative functions in this code, but both of them give me the same error.

#y'-2ty = -t
from sympy import *

t = symbols('t')
y = Function('y')(t)

eqn = (Derivative(y(t)) - (2*t*y(t)), -t)
display(eqn)

ysol = dsolve(eqn,y(t))
print("The solution is ", ysol.lhs, " = ", ysol.rhs)
print("The solution is ") 
display(ysol)

Error:

----> 1 ysol = dsolve(eqn,y(t))

TypeError: 'y' object is not callable
1

There are 1 best solutions below

0
jared On

The line

y = Function('y')(t)

already defines y as a function of t. When you write y(t) later, you're asking sympy to call y as if it's a function (like when you call the print function as print(...)). You have two options: (1) Don't define y as a function of t, i.e.

y = Function('y')

With that change, you will no longer get the error. (2) Keep y defined as it is but later only write y instead of y(t), i.e.

eqn = (Derivative(y) - (2*t*y), -t)

In your question you said you tried y.diff(), but with how you've defined y, that should actually work, so I'm guess you actually did y(t).diff().


Now, you actually have another issue later, which is that you should define eqn as a sympy equation, i.e.

eqn = Eq(Derivative(y) - (2*t*y), -t)

Without that, dsolve will throw an error (it's expecting an equation).


As another minor point, avoid wildcard imports (from X import *) in your code. Some people will do import sympy as smp or import sympy as sp or just import sympy. Then, you would do y = smp.Function("y").