2
votes

I'm trying to solve a differential equation using SymPy in Python. I have two solutions x(t) and y(t), but when I try to multiply these solutions by an integer or float, I get this error: "unsupported operand type(s) for *: 'Equality' and 'float'"

from sympy import symbols, Function, Eq, diff, dsolve, solve

def model():
    t = symbols('t')
    y, x = symbols("y x", cls=Function)
    eq = (Eq(diff(y(t), t), (2 * x(t))), Eq(diff(x(t), t), (2 * y(t))))
    h = dsolve(eq)
    t0 = 0
    x0 = 1
    y0 = 1
    init1 = h[0].rhs.subs(t, t0) - x0
    init2 = h[1].rhs.subs(t, t0) - y0
    S = solve((init1, init2))
    h0 = [h[0].subs(S), h[1].subs(S)]
    for i in range(len(h0)):
        print(2 * h0[i])
    
model()
1
Did you examine all the intermediate steps? When I test code like this I have to use an interactive session, such as isympy. That way I can see what h is, and init1, and most relevant to this error, h0. I'm not enough of a sympy whiz to accurately run the code in my head!hpaulj

1 Answers

2
votes

In your function, h0[i] is a SymPy Equality object. For example, h0[0] is Eq(y(t), exp(2*t)), indicating that y(t) is equal to exp(2*t). You're trying to multiply the whole Equality object with an integer (2), which throws the error.

Instead, to multiply just the term on the right-hand side (RHS) of the Equality object by 2, first extract it with the rhs attribute. So instead of print(2 * h0[i]), it should be:

print(2 * h0[i].rhs)