A Byte of PhysicsLogo

Center of mass computation

The center of mass is a mass-weighted average position. It replaces a collection of particles with one representative point for questions about the system's overall translation. The particles do not have to be located at that point, and the point can even lie in empty space, as it does at the center of a ring.

Point-particle definition

For particles with masses \(m_i\) and position vectors \(\mathbf r_i\), total mass is

\[M=\sum_{i=1}^{N}m_i\]

and the center-of-mass position is

\[\mathbf R_{\mathrm{cm}}=\frac{1}{M}\sum_{i=1}^{N}m_i\mathbf r_i\]

For ordinary classical matter, each mass is positive, so the center of mass of finitely many particles lies in their convex hull. In one dimension it must lie between the leftmost and rightmost particle. It is closer to a more massive particle when the others are fixed.

The numerator has units of mass times length. Dividing by total mass leaves length. All positions must be expressed relative to the same origin and in the same coordinate system before they are combined.

import numpy as np

masses = np.array([1.0, 3.0])
positions = np.array([[0.0, 0.0], [4.0, 2.0]])
assert np.all(masses > 0)
centre = np.sum(masses[:, None] * positions, axis=0) / masses.sum()
print("Centre of mass (m):", centre)

An empty list has no defined center of mass. Silently returning the origin would confuse missing data with a real symmetric system.

One-dimensional example

Place a \(1\,\mathrm{kg}\) mass at \(x_1=0\,\mathrm m\) and a \(3\,\mathrm{kg}\) mass at \(x_2=4\,\mathrm m\). The center is

\[x_{\mathrm{cm}}=\frac{(1)(0)+(3)(4)}{1+3}=3\ \mathrm m\]

The result lies between the masses and nearer the heavier one. If both masses were equal, the center would be the midpoint at \(2\,\mathrm m\). If the second mass grew while positions stayed fixed, the center would approach \(4\,\mathrm m\) without passing it.

The two-body expression can also be rearranged into the useful lever relation

\[m_1(x_{\mathrm{cm}}-x_1)=m_2(x_2-x_{\mathrm{cm}})\]

This is a consequence of the weighted average. It should not be confused with a torque balance unless the stated physical support and forces make that interpretation valid.

Extended bodies and density

For a continuous body, replace the sum with an integral over mass:

\[\mathbf R_{\mathrm{cm}}=\frac{1}{M}\int\mathbf r\,dm\]

If volume density is \(\rho(\mathbf r)\), then

\[M=\int_V\rho\,dV,\qquad \mathbf R_{\mathrm{cm}}=\frac{1}{M}\int_V\mathbf r\rho\,dV\]

Thin wires use linear density and area laminas use surface density. Density must be mass per corresponding measure, not merely a relative brightness or point count unless that quantity is known to be proportional to mass.

Symmetry can remove work. A uniform sphere has its center of mass at its geometric center. A body symmetric under reflection across a plane has its center of mass in that plane, provided its density shares the symmetry. Geometric symmetry of the boundary is not enough when density is nonuniform.

# A rod from x=0 to x=2 m with linear density proportional to x.
edges = np.linspace(0, 2, 1001)
centres = (edges[:-1] + edges[1:]) / 2
cell_masses = centres * np.diff(edges)
centre_estimate = np.sum(cell_masses * centres) / cell_masses.sum()
print(f"Rod centre: {centre_estimate:.6f} m; exact: {4/3:.6f} m")

Refine the cells and compare estimates. Sampling only the boundary does not generally approximate a solid volume integral.

Composite objects and missing pieces

A complicated object can be divided into components whose masses and centers are known:

\[\mathbf R_{\mathrm{cm}}=\frac{\sum_j M_j\mathbf R_j}{\sum_jM_j}\]

Each component can stand for an extended body because its total first moment is equivalent to its mass placed at its own center of mass. A hole can be handled algebraically as removed material with negative contribution, but negative mass is only a bookkeeping device in that calculation. The final physical mass must equal the mass of the material that remains.

When two objects overlap in a decomposition, avoid counting shared material twice. Record component boundaries and density assumptions.

Motion of the center of mass

For constant particle masses, differentiating the position definition gives

\[\mathbf V_{\mathrm{cm}}=\frac{d\mathbf R_{\mathrm{cm}}}{dt}=\frac{1}{M}\sum_i m_i\mathbf v_i=\frac{\mathbf P}{M}\]

Differentiating again and applying Newton's second law gives

\[M\mathbf A_{\mathrm{cm}}=\mathbf F_{\mathrm{external}}\]

Internal forces can produce complex relative motion, deformation, or explosion, but they cannot change the center-of-mass momentum of a closed constant-mass system. A firework's fragments spread around a center of mass that continues along the trajectory set by external forces.

This does not say that the center of mass follows one physical particle or that the entire object can be replaced by a point for every question. Rotation, stress, collision geometry, and gravitational tidal effects require more information than total mass and center position.

Coordinates, frames, and translations

If every particle position is shifted by the same constant vector \(\mathbf a\), then

\[\mathbf r_i'=\mathbf r_i+\mathbf a\quad\Rightarrow\quad\mathbf R_{\mathrm{cm}}'=\mathbf R_{\mathrm{cm}}+\mathbf a\]

This is an important test: changing the origin shifts the answer by exactly the same amount and does not alter relative positions. Rotating all positions should rotate the center by the same rotation.

Positions stored in periodic coordinates require special handling. Values just below the right edge and just above the left edge may be physically adjacent, yet an ordinary arithmetic mean places their center near the middle of the box. Unwrap connected bodies or use a circular-coordinate method before averaging, and state which periodic image was chosen.

Changing systems and variable mass

The simple derivative formulas assume a fixed collection of particles or correctly accounted mass flow. If fuel leaves a rocket, rain enters a cart, or a program changes membership between frames, the center can jump merely because the system definition changed. Momentum carried across the boundary must be included in the dynamics.

For observational data, stable body identifiers matter. Dropping an occluded body or double-counting a detection changes both numerator and denominator. Treat membership as part of the measured state, not as invisible preprocessing.

Numerical accuracy

Very large coordinates combined with small relative separations can lose precision in floating-point arithmetic. Choose a nearby reference point \(\mathbf r_0\) and compute

\[\mathbf R_{\mathrm{cm}}=\mathbf r_0+\frac{1}{M}\sum_i m_i(\mathbf r_i-\mathbf r_0)\]

This is algebraically identical and can reduce cancellation. Pairwise or compensated summation can further improve large reductions. Do not round each weighted contribution; round only the reported result.

Compare the computed point with bounds and symmetries. For positive masses, a result outside the convex hull signals inconsistent coordinates, units, overflow, or an incorrect denominator. Translate and rotate the inputs to check covariance.

Reliability checks

The center of mass compresses a system's translational information into one point. Its calculation is a weighted average, while its motion is governed by external force; both statements depend on a clear boundary, coordinate frame, and mass model.

A worked Python notebook

Place a 1 kilogram mass at the origin and a 3 kilogram mass at a variable position. The question for this calculation is precise: how does centre of mass change when we change second position, while keeping the other choices fixed? The earlier sections explain the physical relationship. Here we turn one part of that relationship into a calculation that you can run, inspect, and change in Google Colab.

Both positions are measured in the same frame and at the same time. Keep that sentence beside the results. A formula can return a number outside its useful range, and a plotting library will usually draw that number without asking whether the physical assumptions still hold. The selected interval is from 0 to 8 m. It gives us a specific domain to discuss instead of leaving the graph's range to a software default.

Use the notebook link above the lesson, run the setup cell, and then run the cells in order. The code below is also included there. NumPy handles the arrays of numerical values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these libraries or notebook cells are unfamiliar, start with Your first physics notebook.

State the relationship before choosing a graph

In this small example, q stands for second position, expressed in m. The output is centre of mass, expressed in m. The equation below uses the numerical values in those units. Any fixed coefficients therefore carry the units needed to make the relation consistent. A value supplied in another unit must be converted before it enters this expression.

\[f(q) = \frac{3 q}{4}\]

This is a function of one changing input. It is not a statement that the physical system has only one variable. We deliberately hold the other inputs fixed so that one cause of variation is visible. Changing several inputs at once would make it harder to tell which change produced the output difference. Write down the held-fixed choices before trying a different experiment.

At 4 m, the expression gives 3 m. This is our reference calculation. It is a prediction of the stated example, not a new measurement. Its displayed digits help us compare implementations. They should not be read as a claim that physical inputs are known to six significant figures.

import numpy as np
import sympy as sp
import matplotlib.pyplot as plt

q = sp.Symbol("q", real=True)
expression = sp.sympify("3*q/4", locals={"q": q})
reference_input = 4.0
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "m")
print("Predicted centre of mass:", reference_output, "m")

sp.Symbol declares a mathematical symbol. It does not assign a numerical measurement to that symbol. subs then replaces the symbol with our chosen input, and float converts the resulting symbolic number into a standard Python numerical value. Keeping these steps separate lets us inspect the equation before numerical substitution. It also prevents a later plot from becoming the only surviving record of the model.

Compare a few cases you can explain

Before drawing hundreds of points, calculate three. The lower endpoint gives 0 m. The midpoint, at 4 m, gives 3 m. The upper endpoint gives 6 m. Read these together with the assumptions: they describe different choices of second position within the same example, with the other inputs held fixed.

These three values are a useful first check, but they do not establish the shape between them. Two endpoints can be equal even when the curve bends or oscillates in between. Likewise, a large change between endpoints does not tell us whether the relationship is linear. We need the equation and intermediate samples to answer those questions.

evaluate = sp.lambdify(q, expression, modules="numpy")
inputs = np.array([0.0, 4.0, 8.0])
outputs = np.asarray(evaluate(inputs), dtype=float)
outputs = np.broadcast_to(outputs, inputs.shape)
for input_value, output_value in zip(inputs, outputs):
    print(f"{input_value:.6g} m -> {output_value:.6g} m")
assert np.all(np.isfinite(outputs))

lambdify turns the symbolic expression into a numerical function. We explicitly select NumPy as its numerical backend so it can accept an array. The same expression now has two useful forms: one for algebra and one for calculating many cases. The assertion checks that the chosen inputs produce finite outputs. It would catch an infinity or an undefined numerical result, but a finite value can still be physically inappropriate.

Make a graph that answers the question

The horizontal axis shows second position; the vertical axis shows centre of mass. Every plotted point is a prediction of the same expression. We mark the reference case separately so that a reader can connect the earlier printed value to its place on the curve. The axis labels include units because a shape without a scale cannot tell us the size of a physical effect.

input_grid = np.linspace(0.0, 8.0, 301)
output_grid = np.asarray(evaluate(input_grid), dtype=float)
output_grid = np.broadcast_to(output_grid, input_grid.shape)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(input_grid, output_grid, label="Stated model")
ax.scatter([reference_input], [reference_output], label="Reference case", zorder=3)
ax.set_xlabel("Second position (m)")
ax.set_ylabel("Centre of mass (m)")
ax.legend()
ax.grid(alpha=0.25)
fig.tight_layout()
plt.show()

Look for a sign change, a turning point, or a region where the curve becomes steep. Connect each feature to the expression rather than to the colour of the line. If the curve has a minimum or maximum, changing the input in opposite directions may have similar effects on the output near that point. If it is nearly straight over a short interval, a local linear approximation may be useful even when the complete expression is nonlinear.

Increasing the number of samples makes the line smoother and may reveal features that a coarse grid missed. It does not improve the physical inputs or enlarge the model's validity range. For quantities that can take only discrete values, use the line as a guide to the relationship and interpret only the allowed input values. A plotting function does not enforce such restrictions for you.

Measure the local sensitivity

A derivative asks a more specific question than the whole graph: how quickly does centre of mass change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 4 m is 0.75 in those ratio units. Locally, the output increases as the input increases. This statement is local; the sign or size of the slope can be different elsewhere on the curve.

\[f'(q) = \frac{3}{4}\]

For a small input change, multiply the derivative by that change to estimate the output change. Then compare that estimate with a fresh evaluation of the full expression. The distinction between these two calculations matters: the derivative gives a tangent approximation, while substitution evaluates the chosen expression at the new point.

slope_expression = sp.diff(expression, q)
slope_at_reference = float(slope_expression.subs(q, reference_input))
changed_input = 4.04
linear_prediction = reference_output + slope_at_reference * (
    changed_input - reference_input
)
full_prediction = float(evaluate(changed_input))
print("Symbolic derivative:", slope_expression)
print("Tangent prediction:", linear_prediction, "m")
print("Full expression:", full_prediction, "m")
print("Approximation difference:", full_prediction - linear_prediction, "m")

Here the changed input is 4.04 m. The tangent estimate is 3.03 m, while the full expression gives 3.03 m. If the two values are close, it means the chosen input change is small enough for this local approximation at this point. It does not mean the entire model is linear. If the slope is zero, a quadratic or higher-order term may supply the leading change instead.

This is also the beginning of uncertainty propagation. If the input has a small stated standard uncertainty, the magnitude of the slope times that uncertainty estimates one contribution to output uncertainty. Do not automatically use the same rule for a wide interval, a discontinuity, a turning point with zero first derivative, or several correlated uncertain inputs. Those situations need more of the model than one slope.

Check the derivative with numerical differences

We can estimate the same slope from values on either side of the reference point. Subtract the lower output from the upper output and divide by twice the input step. Parentheses are essential: the entire output difference must be divided by the entire input interval. Without them, Python can execute a different mathematical expression while still producing a plausible number.

The calculation below uses three decreasing step sizes. Each estimate is compared with the symbolic derivative, so the reference is independent of the numerical difference formula. Near an endpoint, it is acceptable here to evaluate a small extension only because the displayed mathematical expression is smooth there; such a check does not assert that extrapolated values describe additional physical cases.

input_span = 8.0
for fraction in [1e-2, 1e-3, 1e-4]:
    step = input_span * fraction
    upper = float(evaluate(reference_input + step))
    lower = float(evaluate(reference_input - step))
    numerical_slope = (upper - lower) / (2 * step)
    difference = numerical_slope - slope_at_reference
    print(f"step={step:.6g}: slope={numerical_slope:.6g}, difference={difference:.6g}")

For a smooth function, reducing the step often reduces the approximation error at first. Very small steps can eventually make subtraction of nearly equal floating-point values less reliable. Therefore “smaller” is not an unlimited guarantee of “better.” Compare the observed behaviour over a useful range of steps instead of choosing the smallest number the computer can represent.

An absolute slope difference is useful when the expected slope is near zero. A relative difference would divide by a very small reference and could look enormous even when the absolute discrepancy is tiny. Away from zero, a relative difference can help compare quantities with very different scales. The tolerance should reflect the question and the numerical method, rather than a universal decimal threshold copied into every test.

Change the example and preserve the reasoning

Make one copy of the reference calculation before editing it. Choose a second value of second position inside the stated interval, predict whether centre of mass will rise or fall, and then evaluate the expression. Place the prediction and the result in a text cell. If they disagree, identify whether the mistake was in the sign, the unit conversion, the algebra, or the assumption about how the curve behaves.

Next choose a shorter plotting interval around the reference point. Compare the local curve with its tangent approximation. Then widen the interval again. The difference shows why a useful local estimate need not describe the whole range. Keep the axis labels and numerical scale visible when comparing the plots; automatic axis limits can make two different effects appear equally large.

Finally, return to the physical limit stated at the start: Both positions are measured in the same frame and at the same time. Describe one change to the setup that would violate that limit. State what new input, equation, or observation would be needed before trusting an answer in the changed situation. This last step connects the Python experiment to the physics instead of treating successful execution as the only criterion for a useful result.

Before saving, restart the runtime and run all cells in order. A result that depends on an earlier, now-deleted input cell is not reproducible from the saved notebook. Keep unrounded values for later calculations, round only the reported output, and label any new data as measured, assumed, or generated. The graph and printed values should remain traceable to the same expression and the same choices of inputs.

Recover the output change by integrating the slope

There is another way to check that the expression and its derivative describe the same relationship. Add up the small output changes predicted by the slope across the chosen input interval. In the continuous limit, this integral equals the output at the upper endpoint minus the output at the lower endpoint. The result has units of m: the input unit in the integration cancels the input unit in the denominator of the slope.

This statement is about the mathematics of this particular relationship. It does not assign a new physical meaning to an arbitrary area under a graph. For example, an area under force versus distance represents work, while an area under a different pair of quantities may represent something else or have no standard name. Always carry the axis units through the calculation before naming an integral.

slope_function = sp.lambdify(q, slope_expression, modules="numpy")
endpoint_change = float(evaluate(8.0) - evaluate(0.0))
for points in [101, 201, 401]:
    grid = np.linspace(0.0, 8.0, points)
    slopes = np.asarray(slope_function(grid), dtype=float)
    slopes = np.broadcast_to(slopes, grid.shape)
    integrated_change = np.trapezoid(slopes, grid)
    print(
        points,
        "integrated change:",
        integrated_change,
        "endpoint change:",
        endpoint_change,
    )

The trapezoidal rule joins neighbouring slope samples with straight segments and adds their signed areas. A negative contribution remains negative; replacing every slope by its magnitude would calculate a different quantity. Increasing the sample count provides a practical refinement check. If the values do not settle toward the endpoint difference, first inspect the interval, singularities, and array ordering.

Do not conclude that two agreeing calculations prove the model is physically complete. Both use the same selected relationship, so an omitted effect would be omitted from both. Their agreement is evidence that the numerical tools implement that relationship consistently. Comparing with an independent experiment or a more appropriate physical model is a separate test.

Keep this comparison in the notebook when you change the expression. It is particularly useful after adding a coefficient, changing a sign convention, or converting an input unit. A code cell that produces a smooth graph can conceal these mistakes; a second calculation of the same output change gives you another place to notice them.

Sources


Share to: