What an integrator actually does
Nearly every simulation on this site solves the same problem: you know the forces acting on a body right now, and you want its position a moment later. Newton gives you a second-order ODE, a = F(x)/m, and a numerical integrator turns it into a rule for stepping (x, v) forward by a finite time h. Which rule you choose decides whether a planet stays in orbit for an hour of wall-clock time or spirals into the sun by the third minute.
Two properties matter and they are not the same thing. Accuracy is how small the error is after one step (local truncation error) or after a fixed time (global error). Stability is whether the error stays bounded as you keep stepping. A method can be accurate and unstable, or inaccurate and beautifully stable — Velocity Verlet is the second kind, and for physics that is usually what you want.
Explicit Euler: the one that lies
The cheapest scheme evaluates the force once and moves everything with it:
Its local error is O(h²) and its global error O(h) — first order. Worse, for an oscillator it is unconditionally unstable: the amplitude grows every step, no matter how small h is. Simulate a spring or a circular orbit with explicit Euler and the energy climbs monotonically; the planet spirals outward.
The nearly free fix is semi-implicit (symplectic) Euler: update the velocity first, then move the position with the new velocity.
// explicit (forward) Euler — do not use for orbits v += a(x) * h; x += v * h; // v here is the OLD v if you write it in this order
RK4 and Symplectic Integration
RK4 (Runge-Kutta 4) is a fourth-order numerical method for solving ordinary differential equations. It's particularly well-suited for simulating Hamiltonian systems like those found in physics, such as planetary motion or molecular dynamics. Symplectic integration is a specific type of numerical integration technique designed to preserve the key properties of Hamiltonian systems. Unlike simpler methods, it doesn’t suffer from the ‘secular drift’ problem that can plague other higher-order integrators. This means that the energy of the system remains accurately conserved over long periods of time. The core idea behind symplectic integration is to mimic the natural way that physical systems evolve – step by step, while respecting the constraints imposed by their equations of motion. RK4 provides a robust and accurate implementation of this approach, ensuring that the simulation’s results remain reliable even after many steps.
Швидкість Verlet та Leapfrog
Швидкість Verlet є основною для молекулярної динаміки та кожного розв’язника жорсткого тіла в іграх. Вона симетрична, часово обернена, другого порядку і потребує лише однієї оцінки сили на крок, якщо ви зберігаєте прискорення:
// Швидкість Verlet — 2-го порядку, симетрична, 1 оцінка сили/крок x += v * h + 0.5 * aOld * h * h; const aNew = a(x); // єдина оцінка сили v += 0.5 * (aOld + aNew) * h; aOld = aNew;
// Velocity Verlet — 2nd order, symplectic, 1 force eval/step x += v * h + 0.5 * aOld * h * h; const aNew = a(x); // the only force evaluation v += 0.5 * (aOld + aNew) * h; aOld = aNew;
RK4: accurate, not symplectic
Classical fourth-order Runge–Kutta samples the derivative four times per step and blends them. Its global error is O(h⁴), so it is dramatically more accurate per step than Verlet — but it costs four force evaluations, and it is not symplectic. Run RK4 on a closed orbit and the energy decays slowly and monotonically: the planet spirals in. For a chaotic system integrated over a short horizon (the double pendulum, the Lorenz attractor) that is fine and the accuracy is worth it; for a solar system integrated over a million years it is a disaster.
const k1 = f(t, y); const k2 = f(t + h/2, y + h/2 * k1); const k3 = f(t + h/2, y + h/2 * k2); const k4 = f(t + h, y + h * k3); y += h/6 * (k1 + 2*k2 + 2*k3 + k4); // 4 evaluations, O(h⁴), not symplectic
Выбор размера шага
Шаг ограничивается самым быстрым элементом в вашей системе. Для осциллятора с угловой частотой ω, явный метод второго порядка требует примерно h·ω < 2 для устойчивости, и вы хотите значительно меньше — это правило большого пальца: от 20 до 50 шагов на период самого жесткого режима перед тем, как движение выглядит правильно. Для систем частиц аналогичный предел - условие CFL: ни один из частиц не должен пересекать более чем часть радиуса взаимодействия за один шаг.
Две практические привычки. Во-первых, отделите физический шаг от частоты кадров: запустите фиксированный h (например, 1/240 с) внутри цикла накопителя и интерполируйте для рендеринга, в противном случае упавший кадр будет бесшумно изменять поведение вашего интегратора. Во-вторых, постройте общую энергию. Это самый дешевый детектор ошибок — монотонный подъем означает явную Эйлера где-то, монотонное уменьшение означает несимметричный метод или слишком большое затухание, а ограниченная дрожь означает, что вы в порядке.
What this site uses where
This site demonstrates several numerical methods for solving differential equations. We focus on Verlet, Leapfrog, and RK4 (Runge-Kutta 4).
Verlet is a semi-implicit method that conserves energy well, making it suitable for simulating physical systems with constraints.
Leapfrog is an explicit method often used in celestial mechanics to approximate the motion of objects over time. It's less accurate than Verlet for conserving energy but computationally faster.
RK4 is a higher-order implicit method that provides greater accuracy and stability compared to Verlet and Leapfrog, particularly for problems with stiff dynamics.
orbits, N-body, springs, molecular dynamics → Velocity Verlet / Leapfrog cloth, ropes, soft bodies → position Verlet + constraints SPH fluids → Leapfrog with a CFL-limited step double pendulum, Lorenz, chaotic systems → RK4 (short horizon, high accuracy)
Часті запитання
Який інтегратор кращий: Velocity Verlet чи RK4?
Ніхто не домінує. RK4 має четвертий порядок точності, але не симплектичний, тому закриті орбіти втрачають енергію протягом тривалих прогонів; Velocity Verlet має лише другий порядок точності, але зберігає енергію безперервно у межах обмеженої системи та потребує вчетверо менше обчислень сили. Використовуйте Verlet або Leapfrog для довготривалих консервативних систем, RK4 – для коротких, високоточних інтеграцій хаотичних систем.
Чому моя планета спірається назовні?
Практично завжди використовується явний (прямий) Ейлер: положення обчислюється з використанням старої швидкості, що вводить енергію на кожному кроці. Поміняйте два рядки так, щоб положення використовувало оновлену швидкість – це напівнеявний Ейлер, який не потребує додаткових обчислень і є симплектичним.
Чи є Leapfrog та Velocity Verlet різними методами?
Це один і той же метод, написаний по-різному. Для постійного кроку часу вони виробляють ідентичні траєкторії; Leapfrog просто зберігає швидкості на півкроках, тому його кінетична енергія потребує коригування на півкрок перед тим, як її можна порівняти з потенційною енергією.
Спробуйте наживо
Усе, що вище, працює прямо у вашому браузері — відкрийте Double Pendulum і змінюйте параметри під час роботи. Нічого не встановлюється, нічого не завантажується на сервер, уся модель живе в одній вкладці.
▶ Відкрити симуляцію Double Pendulum