Physics Simulation Algorithms in TheAlgorithms/Java: Complete Implementation Guide
Yes, TheAlgorithms/Java includes a dedicated physics package containing classical simulation algorithms for oscillators, projectile motion, elastic collisions, and fundamental physical laws.
TheAlgorithms/Java serves as a comprehensive repository of computer science algorithms implemented in pure Java. Among its specialized collections, the physics simulation algorithms package provides stateless, immutable classes for modeling mechanical systems, trajectories, and forces—making it suitable for educational purposes, physics engines, and scientific computing projects.
Overview of the Physics Package
All physics implementations reside in src/main/java/com/thealgorithms/physics/. The classes are designed as pure-Java, stateless utilities that encapsulate only immutable physical parameters. This architecture ensures thread safety and allows direct integration into larger applications or the provided JUnit test suites (e.g., SimplePendulumRK4Test).
Core Physics Simulation Algorithms
Oscillators and Harmonic Motion
The repository provides numerical and analytical solvers for oscillating systems. SimplePendulumRK4 implements 4th-order Runge-Kutta integration to simulate nonlinear pendulum dynamics step-by-step. For damped systems, DampedOscillator offers a closed-form analytical solution for harmonic motion with friction.
Projectile Motion Solvers
Two complementary classes handle ballistic trajectories. GroundToGroundProjectileMotion calculates simplified ground-to-ground trajectories using standard kinematic formulas. For arbitrary launch heights, ProjectileMotion computes comprehensive flight data including time of flight, horizontal range, and maximum apex—essential for robotics and game development.
Collision Physics
The ElasticCollision2D class solves two-dimensional elastic collisions by applying conservation of momentum and kinetic energy. It accepts mass and velocity vectors for two bodies and returns the post-collision velocity vectors, enabling realistic physics responses without external dependencies.
Fundamental Physical Laws
The package includes direct implementations of classical physics formulas:
CoulombsLawcalculates electrostatic force between point chargesGravitationcomputes Newtonian gravitational attraction between massesSnellLawdetermines refraction angles across media boundariesThinLensprovides optical imaging equations for focal length and magnification
Kinematics Utilities
Kinematics supplies helper methods for unit conversions and basic motion equations, serving as a lightweight utility for coordinate transformations and velocity calculations.
Implementation Examples
Simulating a Simple Pendulum with RK4
The following example demonstrates numerical integration of a nonlinear pendulum using SimplePendulumRK4:
import com.thealgorithms.physics.SimplePendulumRK4;
public class PendulumDemo {
public static void main(String[] args) {
// Length = 1 m, gravity = 9.81 m/s²
SimplePendulumRK4 pendulum = new SimplePendulumRK4(1.0, 9.81);
// Initial state: 30° (≈0.5236 rad) displacement, no initial angular velocity
double[] state = new double[]{Math.toRadians(30), 0.0};
// Simulate for 5 seconds with a step of 0.01 s
double dt = 0.01;
int steps = (int) (5.0 / dt);
double[][] trajectory = pendulum.simulate(state, dt, steps);
// Print the angle (degrees) at each second
for (int i = 0; i <= steps; i += 100) { // every 1 s
double theta = Math.toDegrees(trajectory[i][0]);
System.out.printf("t = %.2f s → θ = %.2f°%n", i * dt, theta);
}
}
}
Computing Projectile Trajectories from Arbitrary Heights
This example calculates a projectile launched from an elevated position using ProjectileMotion:
import com.thealgorithms.physics.ProjectileMotion;
import com.thealgorithms.physics.ProjectileMotion.Result;
public class ProjectileDemo {
public static void main(String[] args) {
double v0 = 50.0; // m/s
double angle = 45.0; // degrees
double height = 1.5; // metres above ground
Result r = ProjectileMotion.calculateTrajectory(v0, angle, height);
System.out.printf("Time of flight: %.2f s%n", r.getTimeOfFlight());
System.out.printf("Horizontal range: %.2f m%n", r.getHorizontalRange());
System.out.printf("Maximum height: %.2f m%n", r.getMaxHeight());
}
}
Solving 2-D Elastic Collisions
The following code resolves a two-body elastic collision using ElasticCollision2D:
import com.thealgorithms.physics.ElasticCollision2D;
import com.thealgorithms.physics.ElasticCollision2D.Velocity;
public class CollisionDemo {
public static void main(String[] args) {
// Masses (kg) and initial velocities (m/s)
double m1 = 2.0, m2 = 1.0;
Velocity v1 = new Velocity(3.0, 0.0);
Velocity v2 = new Velocity(-1.0, 0.0);
// Compute post-collision velocities
Velocity[] result = ElasticCollision2D.compute(m1, v1, m2, v2);
System.out.println("After collision:");
System.out.printf("Body 1 → (%.2f, %.2f) m/s%n", result[0].vx, result[0].vy);
System.out.printf("Body 2 → (%.2f, %.2f) m/s%n", result[1].vx, result[1].vy);
}
}
Summary
- TheAlgorithms/Java provides a complete physics simulation algorithms suite in
src/main/java/com/thealgorithms/physics/ - Runge-Kutta 4th-order integration powers the nonlinear pendulum simulator (
SimplePendulumRK4) - Analytical solvers handle projectile motion (
ProjectileMotion), damped oscillators (DampedOscillator), and elastic collisions (ElasticCollision2D) - Fundamental law implementations include Coulomb's law, gravitation, Snell's law, and thin-lens optics
- All classes are stateless and thread-safe, designed for immediate use in educational or production Java applications
Frequently Asked Questions
What numerical integration method does the pendulum simulator use?
The SimplePendulumRK4 class implements the 4th-order Runge-Kutta (RK4) method as defined in SimplePendulumRK4.java. This explicit integrator provides high accuracy for nonlinear differential equations governing pendulum motion.
Can these physics algorithms handle real-time game engine requirements?
While the algorithms are mathematically correct and stateless, they are designed for educational clarity rather than optimized real-time performance. The RK4 integrator and collision solvers can serve as reference implementations, but game engines may require additional spatial partitioning or vectorization for high-frequency physics ticks.
How do I calculate projectile motion when the launch and landing heights differ?
Use the ProjectileMotion.calculateTrajectory() method as implemented in ProjectileMotion.java. Pass the initial velocity, launch angle, and initial height as parameters; the method returns a Result object containing time of flight, horizontal range, and maximum height calculated via analytic kinematic equations.
Are unit tests available for the physics simulation algorithms?
Yes. The repository includes JUnit test suites such as SimplePendulumRK4Test that validate the numerical accuracy of the integrators and the correctness of the physics formulas against known analytical solutions.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →