pythonmatplotlibgraphsympydifferential-equations

SymPy - plot differential equation graph


I get error when trying to plot a graph : TypeError: Cannot convert expression to float

I also get empty graph:

from sympy import *
from IPython.display import display
init_printing()

import matplotlib.pyplot as plt
import numpy as np


x = symbols('x')
y = Function('y')
ode = Derivative(y(x), x, x) + 9 * y(x)

# Solve the ODE
solution = dsolve(ode, y(x))

# Plot the solution
x_vals = np.linspace(-10, 10, 1000)
y_vals = [solution.rhs.subs({x: val}).evalf() for val in x_vals]

plt.plot(x_vals, y_vals)
plt.xlabel('x')
plt.ylabel('y(x)')
plt.title('Solution to y\'\'(x) + 9y(x) = 0')
plt.grid(True)
plt.show()

python: 3.12
I tried latest Pycharm, Spider(Anaconda) and Jupyter notes (Anaconda)

simply version: 1.13.0
matplotlib: 3.9.1
numpy: 2.0.1

I also tried with lamdify but with same result


x_vals = np.linspace(-10, 10, 1000)

# Convert the symbolic expression to a numerical function

y_expr = solution.rhs 
 
y_func = lambdify(x, y_expr, modules='numpy')

# Evaluate the solution function for all x_vals
y_vals = y_func(x_vals)
                  

plt.plot(x_vals, y_vals)

plt.grid(True)


plt.show()

enter image description here


Solution

  • The unmodified Sympy plot of the solution rhs.

    Your solution.rhs is still undetermined, hence the error.

    You need to provide appropriate initial conditions, using the ips keyword argument to dsolve.

    Also, the Matplotlib contortions are unneeded, Sympy knows how to plot a Sympy function on itself.

    from sympy import *
    
    x = symbols('x')
    y = Function('y')(x) ; y.dot = y.diff(x) ; y.ddot = y.dot.diff(x)
    
    # Solve the ODE y'' + 9y = 0
    solution = dsolve(y.ddot+9*y, ics={y.subs(x,-10):1, y.subs(x,10):1})
    
    # Plot the solution
    p = plot(solution.rhs)
    

    I'd like to mention that p is a Plot object whose attributes you can manipulate (but not as much as a Matplotlib Axes…)