PYTHON
Solving harmonic oscillator problem in Runge-Kutta method | Python
Introduction
Harmonic oscillators are prevalent in physics, and simulating their behavior is crucial for understanding dynamic systems. In this blog post, we'll explore a Python program that uses the Runge-Kutta method to simulate the motion of a harmonic oscillator.
Code
from pylab import *
# Initial conditions
kx1 = kx2 = kx3 = kx4 = 0
kv1 = kv2 = kv3 = kv4 = 0
xn = 1.0
vn = 0.0
h = 0.01
t = 0.0
time = []
displacement = []
w_square = 39.4384 # Adjust this value as needed
# Runge-Kutta method for simulating harmonic oscillation
while t <= 3:
kx1 = vn
kv1 = -1 * xn * w_square
kx2 = vn + 0.5 * h * kv1
kv2 = -1 * (xn + 0.5 * h * kx1) * w_square
kx3 = vn + 0.5 * h * kv2
kv3 = -1 * (xn + 0.5 * h * kv2) * w_square
kx4 = vn + h * kv3
kv4 = -1 * (xn + h * kx3) * w_square
xn = xn + (h * (kx1 + 2 * kx2 + 2 * kx3 + kx4) / 6)
vn = vn + (h * (kv1 + 2 * kv2 + 2 * kv3 + kv4) / 6)
displacement.append(xn)
time.append(t)
t = t + h
# Plotting the results
title('Harmonic Oscillator Simulation')
plot(time, displacement)
xlabel('Time')
ylabel('Displacement')
grid(True)
show()
Output
Explanation
1. Constants and Initial Conditions:
Set initial conditions, step size (h), time (t), and the square of the angular frequency (w_square).
2. Runge-Kutta Method:
Implement the Runge-Kutta method to update the position (xn) and velocity (vn) of the harmonic oscillator at each time step.
3. Plotting:
Use pylab to visualize the simulation results by plotting the displacement over time.
Conclusion
This Python program provides a straightforward example of taking user input, performing a basic arithmetic operation, and displaying the result. Understanding these fundamental concepts is essential for anyone starting their programming journey. Feel free to experiment with different input values and observe how the program accurately calculates the sum. Happy coding!
Post a Comment
0 Comments