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
New contributor
tomopa73 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.