Home > Net >  How do I substitute and array into a sympy equation so I can plot the equation?
How do I substitute and array into a sympy equation so I can plot the equation?

Time:12-12

I have used dsolve to generate a result in the form of an equation in variable result.

I want to plot this equation for the range of values in the x_val array so I can plot it. I do not seem to be able to find a way to use apply the function to the x values.

import sympy as sy
import numpy as np

t,m,k,c  = sy.symbols('t m k c')
x = sy.Function('x')

diffeq = sy.Eq(x(t).diff(t, t) - x(t), sy.cos(t)) 
result = sy.dsolve(diffeq, ics={x(0): 0, sy.diff(x(t), t).subs(t,0): 0})

print(result)

x_val=np.linspace(0,10,100)

CodePudding user response:

You can use evalf() on the right hand side of the returned equality like this.

...
import matplotlib.pyplot as plt

...
ts = np.linspace(0, 10, 100)
xs = [result.rhs.evalf(subs = dict(t=t)) for t in ts]

plt.plot(ts, xs)
plt.show()

CodePudding user response:

@relent95's answer does the job in this case. However, evalf is going to evaluate a symbolic expression into a SymPy's Float number, which is another symbolic expression. This kind of evaluation is slow: if you need to evaluate a symbolic expression over many points, you have two options (in this case).

  1. Use sympy's plot command:
from sympy import plot
plot(result.rhs, (t, 0, 10))
  1. Convert your symbolic expression to a numerical function and evaluate it over a numpy array. In contrast to the previous approach, here you have full control over the appearance of your plot:
import matplotlib.pyplot as plt
from sympy import lambdify

f = lambdify(t, result.rhs)
ts = np.linspace(0, 10, 100)

plt.figure()
plt.plot(ts, f(ts))
plt.show()
  • Related