This repository contains C programs that simulate a damped harmonic oscillator, a fundamental concept in physics and engineering. The simulations model the motion of a mass-spring-damper system using 3 different numerical integration methods to solve the second-order ordinary differential equation (ODE) of motion.
- Explicit Euler Method
- Euler-Cromer Method
- Runge-Kutta RK4 Method
Each method computes the position of the mass over time and outputs the results to a separate data file for analysis and visualization.
A simple first-order integration technique. It updates the position using the velocity from the previous time step. Suitable for basic simulations but may become unstable for stiff or oscillatory systems.
- Source file:
Euler.c - Output:
damped_oscillation_Euler.txt
A modification of the Euler method that uses the updated velocity to compute the new position, offering improved stability for oscillatory systems.
- Source file:
Euler-Cromer.c - Output:
damped_oscillation_Euler_Cromer.txt
A fourth-order integration method that evaluates the system at multiple intermediate points within each time step, providing much higher accuracy.
- Source file:
Runge-Kutta-RK4.c - Output: `damped_oscillation_RK4.txt
To run these simulations, you will need a C compiler (like GCC) installed on your system.
Compiling and Running
-
Clone the repository
-
Compile the
Euler.cprogram:gcc Euler.c -o euler
-
Compile the
Euler-Cromer.cprogram:gcc Euler-Cromer.c -o euler-cromer
-
Run the Euler simulation This will generate a file named
damped_oscillation_Euler.txtwith the simulation data. -
Run the Euler-Cromer simulation This will generate a file named
damped_oscillation_Euler_Cromer.txtwith its data.
Euler.c— Explicit Euler method implementationEuler-Cromer.c— Euler-Cromer method implementationRunge-Kutta-RK4.c— Runge-Kutta RK4 method implementationplot.py— Python script for result visualizationdamped_oscillation_Euler.txt,damped_oscillation_Euler_Cromer.txt,damped_oscillation_RK4.txt— Simulation outputscomparison_plot.png— Comparison plot of all methods
The results from all three methods can be compared using the provided Python script:
- Plot script:
plot.py - Output plot:
comparison_plot.png
python plot.pyLovingly crafted by Hanka Robovska 👩🔬
This project is licensed under the MIT License. For more details, see the LICENSE file.
Feel free to experiment with different physical parameters or time step values to observe how each method behaves!