1

i am trying to use the "subs" function for differential equation but i get the error: "can't convert expression to float"

i tryed to check the type of the arrays, but they all float

import sympy as sym
from sympy.integrals import inverse_laplace_transform
from sympy.abc import s,t,y
import numpy as np

U = 1
G =(s+1)/(s*(s+2))
Y = G*U
y = inverse_laplace_transform(Y, s, t)
tm = np.linspace(0,2,3)
y_val = np.zeros(len(tm))
for i in range(len(tm)):
    y_val[i] = y.subs(t, tm[i])

print(y)
print(y_val)

line 17 y_val[i] = y.subs(t, tm[i]) TypeError: can't convert expression to float

tomer u
  • 31
  • 2

3 Answers3

0

Ths issue here is that, because tm[0] == 0, the evaluated y in the first iteration of your loop is Heaviside(0), which has no defined real value by default (see https://docs.sympy.org/latest/modules/functions/special.html#heaviside). This is because you have

from sympy.functions import exp, Heaviside
assert y == Heaviside(t) / 2 + exp(-2 * t) * Heaviside(t) / 2

The simplest workaround here is defining a linear space excluding 0, for instance

epsilon = 1e-15
tm = np.linspace(epsilon, 2, 3)
michaeldel
  • 2,204
  • 1
  • 13
  • 19
0

Using y_val = np.zeros(len(tm)), the default datatype of array is float. After modifying the code, you find that one of y_val elements is an object, not float. You can use a list object as a placeholder or you can specify the datatype of numpy array as object:

import sympy as sym
from sympy.integrals import inverse_laplace_transform
from sympy.abc import s,t,y
import numpy as np

U = 1
G =(s+1)/(s*(s+2))
Y = G*U
y = inverse_laplace_transform(Y, s, t)
tm = np.linspace(0,2,3)
# y_val = [0 for _ in range(len(tm))]
y_val = np.zeros(len(tm), dtype=object)
for i in range(len(tm)):
    y_val[i] = y.subs(t, tm[i])

print(y_val)

result: [Heaviside(0.0) 0.567667641618306 0.509157819444367]

Masoud
  • 1,270
  • 7
  • 12
0

I have similar problem and your answers work for me, but I still need to put the data into graph.. I modified my problem for this question:

import sympy as sym
from sympy.integrals import inverse_laplace_transform
from sympy.abc import s,t,y
import numpy as np
import matplotlib.pyplot as plt

Y = (5*(1 - 5*s))/(s*(4*(s**2) + s + 1))*(1/s)

y = inverse_laplace_transform(Y, s, t)
tm = np.linspace(1e-15, 20, 100)

y_val = np.zeros(len(tm), dtype=object)
for i in range(len(tm)):
    y_val[i] = y.subs(t, tm[i])

plt.plot(y_val, tm)
plt.show()

Running this code I got same error:

TypeError: can't convert expression to float
  • 1
    Welcome to SO! Please don't add additional questions to questions (especially if they are old): Open a new one and, if useful, link to the other one. – Timus Oct 12 '20 at 20:49