From cb85f0a3e511b4e1a06f1e891f74dc9972924194 Mon Sep 17 00:00:00 2001 From: Mohit Ak Date: Thu, 8 Oct 2026 02:29:17 -0400 Subject: [PATCH] BUG: fix the sign of Flight.potential_energy Flight.potential_energy computed mu * m * (1/(z + R) - 1/R), which is negative for z > 0 and decreases as the rocket climbs. Swap the two terms so the potential energy relative to sea level is positive and grows with altitude. Flight.total_energy inherits the fix. Fixes #1202 --- rocketpy/simulation/flight.py | 2 +- tests/unit/simulation/test_flight.py | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/rocketpy/simulation/flight.py b/rocketpy/simulation/flight.py index 43790110c..1ef208fa4 100644 --- a/rocketpy/simulation/flight.py +++ b/rocketpy/simulation/flight.py @@ -3824,7 +3824,7 @@ def potential_energy(self): return ( standard_gravitational_parameter * total_mass - * (1 / (self.z + self.env.earth_radius) - 1 / self.env.earth_radius) + * (1 / self.env.earth_radius - 1 / (self.z + self.env.earth_radius)) ) # Total Mechanical Energy diff --git a/tests/unit/simulation/test_flight.py b/tests/unit/simulation/test_flight.py index 64082f7a4..a50059f74 100644 --- a/tests/unit/simulation/test_flight.py +++ b/tests/unit/simulation/test_flight.py @@ -553,6 +553,31 @@ def test_max_values(flight_calisto_robust): assert pytest.approx(285.94948, rel=rtol) == test.max_speed +def test_potential_energy_increases_with_altitude(flight_calisto): + """Test that the potential energy grows as the rocket climbs. Between + burn out and apogee the mass is constant, so the change in potential + energy must match m * g * dz. + + Parameters + ---------- + flight_calisto : rocketpy.Flight + Flight object to be tested. See the conftest.py file for more info + regarding this pytest fixture. + """ + test = flight_calisto + burn_out_time = test.rocket.motor.burn_out_time + apogee_time = test.apogee_time + mass = test.rocket.total_mass(apogee_time) + delta_z = test.z(apogee_time) - test.z(burn_out_time) + initial_potential_energy = test.potential_energy(burn_out_time) + final_potential_energy = test.potential_energy(apogee_time) + delta_potential_energy = final_potential_energy - initial_potential_energy + expected_delta = mass * 9.80665 * delta_z + + assert delta_z > 0 + assert pytest.approx(expected_delta, rel=1e-2) == delta_potential_energy + + @pytest.mark.parametrize( "flight_time_attr", ["t_initial", "out_of_rail_time", "apogee_time", "t_final"],