Note: This was a college project for a numerical methods course. It's a learning exercise, so don't take it too seriously! 🎓
This project implements a numerical solver for the 1D wave equation using the leapfrog method (also known as the Verlet method). The implementation solves the wave equation with fixed boundary conditions and compares the numerical solution against the analytical solution.
The code solves the 1D wave equation:
∂²u/∂t² = ∂²u/∂x²
With:
- Boundary conditions: u(0,t) = u(1,t) = 0 (fixed endpoints)
- Initial condition: u(x,0) = sin(πx)
- Analytical solution: u(x,t) = cos(πt) × sin(πx)
-
onda.c- Main wave simulation program- Simulates wave propagation over 1000 time steps
- Outputs numerical solution, analytical solution, and error to
onda.txt
-
leap1derro.c- Error analysis program- Tests the numerical method with varying time steps
- Analyzes convergence and stability
- Outputs error metrics to
erro.txt
Compile the programs using GCC:
# Compile the main wave simulation
gcc -o onda onda.c -lm
# Compile the error analysis program
gcc -o leap1derro leap1derro.c -lmNote: The -lm flag is required to link the math library.
./ondaThis generates onda.txt with columns:
- Spatial index (j)
- Numerical solution u(x,t)
- Analytical solution
- Error (difference between numerical and analytical)
./leap1derroThis generates erro.txt with:
- Time step (k)
- Average error
The leapfrog method is a second-order accurate, explicit time-stepping scheme:
u[n+1] = 2*u[n] - u[n-1] + k²*(u[j+1] - 2*u[j] + u[j-1])
Where:
u[n]is the solution at time step nkis the time step sizejis the spatial index
- Spatial points: 50 (jmax = 50)
- Time step (k): 1.0 (for onda.c), variable (for leap1derro.c)
- Simulation time: 1000 time units (onda.c), 10 time units (leap1derro.c)
The output files (onda.txt and erro.txt) can be visualized using tools like:
- gnuplot
- MATLAB/Octave
- Python (matplotlib, numpy)
# Plot wave evolution
plot 'onda.txt' using 1:2 with lines title 'Numerical'
# Plot error vs time step
plot 'erro.txt' using 1:2 with points title 'Error'The leapfrog method has a stability condition (CFL condition):
k ≤ h
Where h is the spatial step size (h = 1/(jmax-1) ≈ 0.02). The current configuration uses k=1.0 in onda.c, which may not satisfy the stability condition. For stable results, consider reducing the time step.
- The time step
k=1.0inonda.cmay be too large for stability - No command-line argument parsing (parameters are hardcoded)
- Limited error handling for file I/O operations
This project is licensed under the terms specified in the LICENSE file.
Since this is a completed college project, contributions are not being actively sought. However, feel free to fork and experiment!
- Leapfrog integration: https://en.wikipedia.org/wiki/Leapfrog_integration
- Wave equation: https://en.wikipedia.org/wiki/Wave_equation
- Numerical analysis textbooks on finite difference methods