Python(sympy) : How to graph smoothly in 2nd ODE solution with Sympy?

Question:

I’m studing about structural dynamic analysis.
I solved a problem : 1 degree of freedom

The question is
m*y” + cy’ + ky = 900 sin(5.3x)
m=6938.78, c=5129.907, k=379259, y is the function of x

I solved it’s response using by Python and Sympy library.
I drew the response by pyplot. But it’s shape is not smooth like below
enter image description here

How can I draw the respone smoothly?

I tried to draw smoothly by substituting each x to y by numpy, but could not insert x into sin(5.3x).

from sympy import *
import matplotlib.pyplot as plt

x, y=symbols("x, y")
f=symbols('f',cls=Function)
y=f(x)

eq=Eq( 6938.78*diff(y,x,2)  +  5129.907*diff(y,x) + 379259*y-900*sin(5.3*x),0)

eq_done=dsolve(eq,y, ics={  f(0):0,  diff(y,x).subs(x,0):0   }  )

plot(eq_done.rhs,(x,0,10))
Asked By: SM KIM

||

Answers:

One way to make the graph of the response smoother is to increase the number of points at which the function is evaluated. By default, the plot function in SymPy uses a relatively small number of points to plot the function, which can cause the plot to appear jagged. You can increase the number of points used by specifying the numpoints parameter in the plot function. For example, you can try using plot(eq_done.rhs, (x, 0, 10), numpoints=500) to increase the number of points used and see if that makes the plot smoother.

Another way to smooth the plot is to use a different plotting library, such as matplotlib, which has more sophisticated smoothing algorithms. You can use matplotlib to plot the function by converting the SymPy expression to a lambda function and then passing that function to matplotlib’s plot function.

Here is an example of how you could do this:

from sympy import *
import matplotlib.pyplot as plt

x, y = symbols("x, y")
f = symbols('f', cls=Function)
y = f(x)

eq = Eq(6938.78 * diff(y, x, 2) + 5129.907 * diff(y, x) + 379259 * y - 900 * sin(5.3 * x), 0)
eq_done = dsolve(eq, y, ics={f(0): 0, diff(y, x).subs(x, 0): 0})

# Convert the SymPy expression to a lambda function
y_func = lambdify(x, eq_done.rhs, "numpy")

# Use matplotlib to plot the function
x_values = np.linspace(0, 10, 500)  # Generate 500 x-values between 0 and 10
y_values = y_func(x_values)
plt.plot(x_values, y_values)
plt.show()

This should produce a smoother plot of the response.

Answered By: featherless
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.