Skip to content

Comparing Integrator Performance

In this example, we'll compare the performance of different numerical integrators (RK4, RKF45, DP54, and RKN1210) by propagating a satellite orbit over 7 days and analyzing their accuracy and efficiency. We'll measure integration quality by tracking how well each method conserves orbital energy and angular momentum—quantities that should remain constant in two-body orbital dynamics.


Setup

First, we import the necessary libraries:

1
2
3
4
5
6
import pathlib
import os
import sys
import brahe as bh
import numpy as np
import plotly.graph_objects as go

Then define the two-body gravitational dynamics function:

1
2
3
4
5
6
7
8
9
def dynamics(t, state):
    """Two-body gravitational dynamics: acceleration = -mu/r^3 * r"""
    r = state[0:3]  # Position vector (m)
    v = state[3:6]  # Velocity vector (m/s)

    r_mag = np.linalg.norm(r)  # Distance from Earth center (m)
    a = -bh.GM_EARTH / (r_mag**3) * r  # Gravitational acceleration (m/s^2)

    return np.concatenate([v, a])  # Return [velocity, acceleration]

We also need helper functions to calculate orbital energy and angular momentum:

def calculate_specific_energy(state):
    """Calculate specific orbital energy: E = v^2/2 - mu/r (J/kg)"""
    r_mag = np.linalg.norm(state[0:3])
    v_mag = np.linalg.norm(state[3:6])
    return 0.5 * v_mag**2 - bh.GM_EARTH / r_mag


def calculate_angular_momentum(state):
    """Calculate specific angular momentum: h = r × v (m^2/s)"""
    r = state[0:3]
    v = state[3:6]
    return np.cross(r, v)

Initial Conditions

We set up a sun-synchronous LEO satellite orbit at 500 km altitude and calculate reference values for comparison:

# Define orbital elements
a = bh.R_EARTH + 500e3  # Semi-major axis: 500 km altitude (m)
e = 0.001  # Eccentricity: nearly circular
i = 97.8  # Inclination: sun-synchronous (degrees)
raan = 0.0  # Right ascension of ascending node (degrees)
argp = 0.0  # Argument of periapsis (degrees)
M = 0.0  # Mean anomaly (degrees)

# Convert orbital elements to Cartesian state vector
oe = np.array([a, e, i, raan, argp, M])
state0 = bh.state_koe_to_eci(oe, bh.AngleFormat.DEGREES)

# Calculate reference values
orbital_period = bh.orbital_period(a)
initial_energy = calculate_specific_energy(state0)
initial_h = calculate_angular_momentum(state0)
h_magnitude_initial = np.linalg.norm(initial_h)

# Set integration time to 7 days
t_end = 7 * 24 * 3600.0  # 7 days in seconds
n_orbits = t_end / orbital_period

This gives us a baseline: the orbital period (~95 minutes) and the initial conserved quantities (energy and angular momentum magnitude). Over 7 days, the satellite will complete approximately 106.5 orbits.

Running Each Integrator

Now we'll propagate the orbit using each of the four integrators, tracking the angular momentum error at regular intervals.

RK4 - Fixed-Step Integrator

RK4 uses a fixed time step throughout the integration. We'll use 10-second steps:

dt = 10.0  # 10 second steps
config_rk4 = bh.IntegratorConfig.fixed_step(step_size=dt)
integrator_rk4 = bh.RK4Integrator(6, dynamics, config=config_rk4)

# Storage for trajectory analysis
times_rk4 = []
h_errors_rk4 = []

t = 0.0
state = state0.copy()
steps = 0
while t < t_end:
    state = integrator_rk4.step(t, state, dt)
    t += dt
    steps += 1

    # Store data every 10 steps for plotting
    if steps % 10 == 0:
        h = calculate_angular_momentum(state)
        h_error = abs(np.linalg.norm(h) - h_magnitude_initial)
        times_rk4.append(t / 86400.0)  # Convert to days
        h_errors_rk4.append(h_error)

# Final results
r_mag = np.linalg.norm(state[0:3])
final_energy = calculate_specific_energy(state)
energy_error = abs(final_energy - initial_energy)
h_final = calculate_angular_momentum(state)
h_error_final = abs(np.linalg.norm(h_final) - h_magnitude_initial)

With a fixed 10-second step size, RK4 takes 60,480 steps over 7 days. While this is reliable and predictable, it doesn't adapt to the problem dynamics.

RKF45 - Adaptive Integrator

RKF45 (Runge-Kutta-Fehlberg) automatically adjusts its step size based on local error estimates:

abs_tol = 1e-10
rel_tol = 1e-9
config_adaptive = bh.IntegratorConfig.adaptive(abs_tol=abs_tol, rel_tol=rel_tol)
integrator_rkf45 = bh.RKF45Integrator(6, dynamics, config=config_adaptive)

times_rkf45 = []
h_errors_rkf45 = []

t = 0.0
state = state0.copy()
dt_current = 10.0
steps = 0
sample_count = 0
while t < t_end:
    result = integrator_rkf45.step(t, state, min(dt_current, t_end - t))
    t += result.dt_used
    state = result.state
    dt_current = result.dt_next
    steps += 1

    # Sample at approximately same rate as RK4
    sample_count += 1
    if sample_count % 10 == 0:
        h = calculate_angular_momentum(state)
        h_error = abs(np.linalg.norm(h) - h_magnitude_initial)
        times_rkf45.append(t / 86400.0)  # Convert to days
        h_errors_rkf45.append(h_error)

r_mag = np.linalg.norm(state[0:3])
final_energy = calculate_specific_energy(state)
energy_error = abs(final_energy - initial_energy)
h_final = calculate_angular_momentum(state)
h_error_final = abs(np.linalg.norm(h_final) - h_magnitude_initial)

RKF45 completes the same 7-day propagation in only 15,687 steps by taking larger steps when the error is small and smaller steps when more accuracy is needed.

DP54 - Dormand-Prince Integrator

DP54 is another adaptive method, often more efficient than RKF45:

integrator_dp54 = bh.DP54Integrator(6, dynamics, config=config_adaptive)

times_dp54 = []
h_errors_dp54 = []

t = 0.0
state = state0.copy()
dt_current = 10.0
steps = 0
sample_count = 0
while t < t_end:
    result = integrator_dp54.step(t, state, min(dt_current, t_end - t))
    t += result.dt_used
    state = result.state
    dt_current = result.dt_next
    steps += 1

    sample_count += 1
    if sample_count % 10 == 0:
        h = calculate_angular_momentum(state)
        h_error = abs(np.linalg.norm(h) - h_magnitude_initial)
        times_dp54.append(t / 86400.0)  # Convert to days
        h_errors_dp54.append(h_error)

r_mag = np.linalg.norm(state[0:3])
final_energy = calculate_specific_energy(state)
energy_error = abs(final_energy - initial_energy)
h_final = calculate_angular_momentum(state)
h_error_final = abs(np.linalg.norm(h_final) - h_magnitude_initial)

DP54 is slightly more efficient, requiring 14,264 steps with the same tolerance settings.

RKN1210 - High-Precision Integrator

RKN1210 is a high-order Runge-Kutta-Nyström method designed for second-order differential equations. We configure it with tighter tolerances:

abs_tol_hp = 1e-12
rel_tol_hp = 1e-11
config_high_precision = bh.IntegratorConfig.adaptive(
    abs_tol=abs_tol_hp, rel_tol=rel_tol_hp
)
integrator_rkn1210 = bh.RKN1210Integrator(6, dynamics, config=config_high_precision)

times_rkn1210 = []
h_errors_rkn1210 = []

t = 0.0
state = state0.copy()
dt_current = 10.0
steps = 0
sample_count = 0
while t < t_end:
    result = integrator_rkn1210.step(t, state, min(dt_current, t_end - t))
    t += result.dt_used
    state = result.state
    dt_current = result.dt_next
    steps += 1

    sample_count += 1
    if sample_count % 10 == 0:
        h = calculate_angular_momentum(state)
        h_error = abs(np.linalg.norm(h) - h_magnitude_initial)
        times_rkn1210.append(t / 86400.0)  # Convert to days
        h_errors_rkn1210.append(h_error)

r_mag = np.linalg.norm(state[0:3])
final_energy = calculate_specific_energy(state)
energy_error = abs(final_energy - initial_energy)
h_final = calculate_angular_momentum(state)
h_error_final = abs(np.linalg.norm(h_final) - h_magnitude_initial)

RKN1210 achieves much higher accuracy with only 945 steps-over 50× fewer than RK4!

Comparison Summary

Here's the summary table showing each integrator's performance:

Output:

======================================================================
COMPARISON SUMMARY (7 days / 106.5 orbits)
======================================================================

Integrator   Type            Steps    Energy Error    |h| Error
----------------------------------------------------------------------
RK4          Fixed-step      60480    8.951e-02       8.085e+01      
RKF45        Adaptive        15687    1.665e+01       1.504e+04      
DP54         Adaptive        14268    3.319e+00       2.999e+03      
RKN1210      High-precision  945      4.869e-05       4.404e-02  

Key observations:

  • RK4 requires many steps (60,480) with moderate accumulated error
  • RKF45 and DP54 reduce steps by ~4× but show more energy/momentum drift
  • RKN1210 achieves the best accuracy with far fewer steps (~64× fewer than RK4)

The energy and angular momentum errors reveal an important pattern: adaptive low-order methods (RKF45, DP54) can accumulate more error over long integrations despite taking fewer steps, while the high-order RKN1210 maintains excellent conservation properties.

Angular Momentum Conservation

To visualize how each integrator performs over time, we plot the angular momentum magnitude error:

Full Code Example

comparing_methods.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import pathlib
import os
import sys
import brahe as bh
import numpy as np
import plotly.graph_objects as go

bh.initialize_eop()

# Configuration for output files
SCRIPT_NAME = pathlib.Path(__file__).stem
OUTDIR = pathlib.Path(os.getenv("BRAHE_FIGURE_OUTPUT_DIR", "./docs/figures/"))
os.makedirs(OUTDIR, exist_ok=True)

# ============================================================================
# SETUP: Define the problem
# ============================================================================


# Define dynamics function for two-body orbital mechanics
# State vector: [x, y, z, vx, vy, vz] in meters and meters/second
def dynamics(t, state):
    """Two-body gravitational dynamics: acceleration = -mu/r^3 * r"""
    r = state[0:3]  # Position vector (m)
    v = state[3:6]  # Velocity vector (m/s)

    r_mag = np.linalg.norm(r)  # Distance from Earth center (m)
    a = -bh.GM_EARTH / (r_mag**3) * r  # Gravitational acceleration (m/s^2)

    return np.concatenate([v, a])  # Return [velocity, acceleration]




def calculate_specific_energy(state):
    """Calculate specific orbital energy: E = v^2/2 - mu/r (J/kg)"""
    r_mag = np.linalg.norm(state[0:3])
    v_mag = np.linalg.norm(state[3:6])
    return 0.5 * v_mag**2 - bh.GM_EARTH / r_mag


def calculate_angular_momentum(state):
    """Calculate specific angular momentum: h = r × v (m^2/s)"""
    r = state[0:3]
    v = state[3:6]
    return np.cross(r, v)




# ============================================================================
# INITIAL CONDITIONS: LEO satellite orbit
# ============================================================================

# Define orbital elements
a = bh.R_EARTH + 500e3  # Semi-major axis: 500 km altitude (m)
e = 0.001  # Eccentricity: nearly circular
i = 97.8  # Inclination: sun-synchronous (degrees)
raan = 0.0  # Right ascension of ascending node (degrees)
argp = 0.0  # Argument of periapsis (degrees)
M = 0.0  # Mean anomaly (degrees)

# Convert orbital elements to Cartesian state vector
oe = np.array([a, e, i, raan, argp, M])
state0 = bh.state_koe_to_eci(oe, bh.AngleFormat.DEGREES)

# Calculate reference values
orbital_period = bh.orbital_period(a)
initial_energy = calculate_specific_energy(state0)
initial_h = calculate_angular_momentum(state0)
h_magnitude_initial = np.linalg.norm(initial_h)

# Set integration time to 7 days
t_end = 7 * 24 * 3600.0  # 7 days in seconds
n_orbits = t_end / orbital_period

# Print problem setup
print("=" * 70)
print("COMPARING INTEGRATORS ON TWO-BODY ORBITAL DYNAMICS")
print("=" * 70)
print(f"Orbit altitude: {(a - bh.R_EARTH) / 1e3:.1f} km")
print(f"Inclination: {i:.1f}°")
print(f"Orbital period: {orbital_period / 60:.2f} minutes")
print(f"Initial energy: {initial_energy:.6e} J/kg")
print(f"Initial |h|: {h_magnitude_initial:.6e} m²/s")
print(f"Integration duration: 7 days ({n_orbits:.1f} orbits)")
print("=" * 70)
print()

# Store results for comparison
results = []


# ============================================================================
# INTEGRATOR 1: RK4 (Fixed-step)
# ============================================================================

print("1. RK4 - Fourth-order Runge-Kutta (Fixed-step)")
print("-" * 70)

dt = 10.0  # 10 second steps
config_rk4 = bh.IntegratorConfig.fixed_step(step_size=dt)
integrator_rk4 = bh.RK4Integrator(6, dynamics, config=config_rk4)

# Storage for trajectory analysis
times_rk4 = []
h_errors_rk4 = []

t = 0.0
state = state0.copy()
steps = 0
while t < t_end:
    state = integrator_rk4.step(t, state, dt)
    t += dt
    steps += 1

    # Store data every 10 steps for plotting
    if steps % 10 == 0:
        h = calculate_angular_momentum(state)
        h_error = abs(np.linalg.norm(h) - h_magnitude_initial)
        times_rk4.append(t / 86400.0)  # Convert to days
        h_errors_rk4.append(h_error)

# Final results
r_mag = np.linalg.norm(state[0:3])
final_energy = calculate_specific_energy(state)
energy_error = abs(final_energy - initial_energy)
h_final = calculate_angular_momentum(state)
h_error_final = abs(np.linalg.norm(h_final) - h_magnitude_initial)

print(f"Configuration: Fixed step size = {dt} seconds")
print(f"Steps taken: {steps}")
print(f"Final altitude: {(r_mag - bh.R_EARTH) / 1e3:.3f} km")
print(f"Energy error: {energy_error:.3e} J/kg")
print(f"Angular momentum error: {h_error_final:.3e} m²/s")
print()

results.append(
    {
        "integrator": "RK4",
        "type": "Fixed-step",
        "steps": steps,
        "energy_error": energy_error,
        "h_error": h_error_final,
        "times": times_rk4,
        "h_errors": h_errors_rk4,
    }
)


# ============================================================================
# INTEGRATOR 2: RKF45 (Adaptive)
# ============================================================================

print("2. RKF45 - Runge-Kutta-Fehlberg (Adaptive)")
print("-" * 70)

abs_tol = 1e-10
rel_tol = 1e-9
config_adaptive = bh.IntegratorConfig.adaptive(abs_tol=abs_tol, rel_tol=rel_tol)
integrator_rkf45 = bh.RKF45Integrator(6, dynamics, config=config_adaptive)

times_rkf45 = []
h_errors_rkf45 = []

t = 0.0
state = state0.copy()
dt_current = 10.0
steps = 0
sample_count = 0
while t < t_end:
    result = integrator_rkf45.step(t, state, min(dt_current, t_end - t))
    t += result.dt_used
    state = result.state
    dt_current = result.dt_next
    steps += 1

    # Sample at approximately same rate as RK4
    sample_count += 1
    if sample_count % 10 == 0:
        h = calculate_angular_momentum(state)
        h_error = abs(np.linalg.norm(h) - h_magnitude_initial)
        times_rkf45.append(t / 86400.0)  # Convert to days
        h_errors_rkf45.append(h_error)

r_mag = np.linalg.norm(state[0:3])
final_energy = calculate_specific_energy(state)
energy_error = abs(final_energy - initial_energy)
h_final = calculate_angular_momentum(state)
h_error_final = abs(np.linalg.norm(h_final) - h_magnitude_initial)

print(f"Configuration: abs_tol={abs_tol}, rel_tol={rel_tol}")
print(f"Steps taken: {steps}")
print(f"Final altitude: {(r_mag - bh.R_EARTH) / 1e3:.3f} km")
print(f"Energy error: {energy_error:.3e} J/kg")
print(f"Angular momentum error: {h_error_final:.3e} m²/s")
print()

results.append(
    {
        "integrator": "RKF45",
        "type": "Adaptive",
        "steps": steps,
        "energy_error": energy_error,
        "h_error": h_error_final,
        "times": times_rkf45,
        "h_errors": h_errors_rkf45,
    }
)


# ============================================================================
# INTEGRATOR 3: DP54 (Adaptive)
# ============================================================================

print("3. DP54 - Dormand-Prince 5(4) (Adaptive)")
print("-" * 70)

integrator_dp54 = bh.DP54Integrator(6, dynamics, config=config_adaptive)

times_dp54 = []
h_errors_dp54 = []

t = 0.0
state = state0.copy()
dt_current = 10.0
steps = 0
sample_count = 0
while t < t_end:
    result = integrator_dp54.step(t, state, min(dt_current, t_end - t))
    t += result.dt_used
    state = result.state
    dt_current = result.dt_next
    steps += 1

    sample_count += 1
    if sample_count % 10 == 0:
        h = calculate_angular_momentum(state)
        h_error = abs(np.linalg.norm(h) - h_magnitude_initial)
        times_dp54.append(t / 86400.0)  # Convert to days
        h_errors_dp54.append(h_error)

r_mag = np.linalg.norm(state[0:3])
final_energy = calculate_specific_energy(state)
energy_error = abs(final_energy - initial_energy)
h_final = calculate_angular_momentum(state)
h_error_final = abs(np.linalg.norm(h_final) - h_magnitude_initial)

print(f"Configuration: abs_tol={abs_tol}, rel_tol={rel_tol}")
print(f"Steps taken: {steps}")
print(f"Final altitude: {(r_mag - bh.R_EARTH) / 1e3:.3f} km")
print(f"Energy error: {energy_error:.3e} J/kg")
print(f"Angular momentum error: {h_error_final:.3e} m²/s")
print()

results.append(
    {
        "integrator": "DP54",
        "type": "Adaptive",
        "steps": steps,
        "energy_error": energy_error,
        "h_error": h_error_final,
        "times": times_dp54,
        "h_errors": h_errors_dp54,
    }
)


# ============================================================================
# INTEGRATOR 4: RKN1210 (High-precision adaptive)
# ============================================================================

print("4. RKN1210 - Runge-Kutta-Nyström 12(10) (High-precision)")
print("-" * 70)

abs_tol_hp = 1e-12
rel_tol_hp = 1e-11
config_high_precision = bh.IntegratorConfig.adaptive(
    abs_tol=abs_tol_hp, rel_tol=rel_tol_hp
)
integrator_rkn1210 = bh.RKN1210Integrator(6, dynamics, config=config_high_precision)

times_rkn1210 = []
h_errors_rkn1210 = []

t = 0.0
state = state0.copy()
dt_current = 10.0
steps = 0
sample_count = 0
while t < t_end:
    result = integrator_rkn1210.step(t, state, min(dt_current, t_end - t))
    t += result.dt_used
    state = result.state
    dt_current = result.dt_next
    steps += 1

    sample_count += 1
    if sample_count % 10 == 0:
        h = calculate_angular_momentum(state)
        h_error = abs(np.linalg.norm(h) - h_magnitude_initial)
        times_rkn1210.append(t / 86400.0)  # Convert to days
        h_errors_rkn1210.append(h_error)

r_mag = np.linalg.norm(state[0:3])
final_energy = calculate_specific_energy(state)
energy_error = abs(final_energy - initial_energy)
h_final = calculate_angular_momentum(state)
h_error_final = abs(np.linalg.norm(h_final) - h_magnitude_initial)

print(f"Configuration: abs_tol={abs_tol_hp}, rel_tol={rel_tol_hp}")
print(f"Steps taken: {steps}")
print(f"Final altitude: {(r_mag - bh.R_EARTH) / 1e3:.3f} km")
print(f"Energy error: {energy_error:.3e} J/kg")
print(f"Angular momentum error: {h_error_final:.3e} m²/s")
print()

results.append(
    {
        "integrator": "RKN1210",
        "type": "High-precision",
        "steps": steps,
        "energy_error": energy_error,
        "h_error": h_error_final,
        "times": times_rkn1210,
        "h_errors": h_errors_rkn1210,
    }
)


# ============================================================================
# COMPARISON SUMMARY
# ============================================================================

print("=" * 70)
print("COMPARISON SUMMARY (7 days / {:.1f} orbits)".format(n_orbits))
print("=" * 70)
print()
print(
    f"{'Integrator':<12} {'Type':<15} {'Steps':<8} {'Energy Error':<15} {'|h| Error':<15}"
)
print("-" * 70)
for r in results:
    print(
        f"{r['integrator']:<12} {r['type']:<15} {r['steps']:<8} "
        f"{r['energy_error']:<15.3e} {r['h_error']:<15.3e}"
    )
print()
print("Key Observations:")
print("• RK4 requires many steps with accumulated drift in conserved quantities")
print("• RKF45 and DP54 adapt step size but show energy/momentum drift")
print("• RKN1210 maintains best conservation with far fewer steps")
print("• Angular momentum conservation indicates integration quality")
print("=" * 70)


# ============================================================================
# VISUALIZATION: Angular Momentum Conservation
# ============================================================================

print("\nGenerating angular momentum conservation plot...")

# Create plotly figure
fig = go.Figure()

# Add traces for each integrator
fig.add_trace(
    go.Scatter(
        x=results[0]["times"],
        y=results[0]["h_errors"],
        mode="lines",
        name="RK4 (Fixed-step)",
        line=dict(color="steelblue", width=2),
        hovertemplate="Day: %{x:.2f}<br>|Δh|: %{y:.3e} m²/s<extra></extra>",
    )
)

fig.add_trace(
    go.Scatter(
        x=results[1]["times"],
        y=results[1]["h_errors"],
        mode="lines",
        name="RKF45 (Adaptive)",
        line=dict(color="coral", width=2),
        hovertemplate="Day: %{x:.2f}<br>|Δh|: %{y:.3e} m²/s<extra></extra>",
    )
)

fig.add_trace(
    go.Scatter(
        x=results[2]["times"],
        y=results[2]["h_errors"],
        mode="lines",
        name="DP54 (Adaptive)",
        line=dict(color="green", width=2),
        hovertemplate="Day: %{x:.2f}<br>|Δh|: %{y:.3e} m²/s<extra></extra>",
    )
)

fig.add_trace(
    go.Scatter(
        x=results[3]["times"],
        y=results[3]["h_errors"],
        mode="lines",
        name="RKN1210 (High-precision)",
        line=dict(color="grey", width=2),
        hovertemplate="Day: %{x:.2f}<br>|Δh|: %{y:.3e} m²/s<extra></extra>",
    )
)

# Configure axes
axis_config = {
    "title_font": {"size": 11},
    "tickfont": {"size": 10},
}

fig.update_xaxes(title_text="Time (days)", **axis_config)
fig.update_yaxes(
    title_text="Angular Momentum Error |Δh| (m²/s)", type="log", **axis_config
)

fig.update_layout(
    title="Angular Momentum Conservation Over 7 Days",
    showlegend=True,
    legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01, font=dict(size=10)),
)

print("Comparison complete!")

See Also