I was plotting the energy variation in a mass-spring system. If I define the initial conditions to be at maximum displacement from the origin, the potential energy is plotted correctly but kinetic energy isn't. However, if I define the initial conditions to be at the zero position and maximum velocity, kinetic energy is plotted correctly but the potential energy isn't. Where is the problem exactly?

import numpy as np
import math
import matplotlib.pyplot as plt
import scipy.integrate as integrate

# Potential energy V and kinetic energy KE
V = []
KE = []
# Defining the differential equation regarding springs 
def spring(x, t, b, w, p):
  return np.array([x[1], -b*x[1] - w*w*(x[0])**(p-1)])

# Defining some parameters
b = 0.0 
w = math.pi/2  
p = 2 

# initial condition and timeframe 
x_init = np.array([0.0, 1.0]) # Initial displacement and initial velocity respectively
t = np.linspace(0, 50, 10000)  

# Solving the differential equation
solution = integrate.odeint(spring, x_init, t, args=(b, w, p))

# Calculating the KE and V for the system
for i in solution[:, 0]:
  k = 10
  V.append((1/2) * k * i**2)

for i in solution[:, 1]:
  m = 1
  KE.append(1/2 * m * i**2)  

# Defining mechanical energy ME to be the sum of both energies.
ME = np.add(V, KE)

# Plotting the results
plt.plot(t, V, color = 'red')
plt.plot(t, KE, color = 'green')
plt.plot(t, ME, color = 'blue')


1 Answer 1


You've defined your potential energy incorrectly.

Your spring forcing function is $$ F = b x + w^2 x^{p-1} $$ The change in potential energy is defined as $$ \Delta V = \int_{x_0}^{x_1} F dx = \left.\frac{1}{2} b x^2 + \frac{w^2}{p} x^p \right|_{x_0}^{x_1} $$ Substituting in $x_0 = 0$ and your constants for $b$, $w$, and $p$ gives $$ V(x) = \frac{\pi^2}{8} x^2 $$ Using this definition of potential energy you get the correct plots where total energy is always constant: enter image description here

  • 1
    $\begingroup$ Oh right, sorry. I was working on forces and forgot that I defined the potential energy differently :) Thanks a lot. $\endgroup$ Apr 7, 2023 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.