A physics graphing widget can report the right displacement and still give the wrong distance. The trap is taking the absolute value of each trapezoid when an interval crosses zero velocity. The area above and below the axis has already cancelled inside that trapezoid.
This comes up in one-dimensional motion. For background on the physics, see tutorgum’s guide to velocity–time graphs.
Split at the crossing
Assume the plotted segment is straight between two velocity samples. With a 4-second interval that goes from +3 m/s to −1 m/s, the velocity crosses zero at 3 seconds. The positive triangle has area 4.5 m and the negative one has area −0.5 m. Displacement is 4 m; distance is 5 m.
function segmentMotion(t0, v0, t1, v1) { const dt = t1 - t0; if (!Number.isFinite(dt) || dt <= 0 || !Number.isFinite(v0) || !Number.isFinite(v1)) { throw new RangeError("Use finite velocities and increasing times."); } const displacement = dt * (v0 + v1) / 2; const crosses = (v0 < 0 && v1 > 0) || (v0 > 0 && v1 < 0); if (!crosses) return { displacement, distance: Math.abs(displacement) }; const left = dt * (Math.abs(v0) / (Math.abs(v0) + Math.abs(v1))); const right = dt - left; const distance = (left * Math.abs(v0) + right * Math.abs(v1)) / 2; return { displacement, distance }; } console.log(segmentMotion(0, 3, 4, -1)); // { displacement: 4, distance: 5 } For a sampled graph, run the function on every pair of adjacent points and add the signed displacements and unsigned distances separately. A sample of zero at the end of a segment is already on the axis, so it does not require a split. A test worth keeping is segmentMotion(0, 2, 2, -2): displacement is zero but distance is 2 m. This method is exact for a piecewise-linear graph; a curve between samples gives an approximation.
