A Byte of PhysicsLogo

Flow rate and continuity

Flow rate measures how much fluid crosses an oriented surface per time. Continuity is the mass-conservation statement connecting those crossings to storage inside a region. The familiar rule that a narrower pipe has faster flow is one useful special case, not the full law.

Volume flow rate

For uniform velocity perpendicular to a flat section of area \(A\), volume flow rate is

\[Q=Av\]

Its SI units are cubic meters per second. In a time interval \(\Delta t\), the volume crossing the section is

\[\Delta V=Q\Delta t\]

For nonuniform velocity or an oblique surface, integrate the normal component:

\[Q=\int_A\mathbf v\cdot\hat{\mathbf n}\,dA\]

The unit normal \(\hat{\mathbf n}\) sets the sign. Flow with the normal is positive; flow against it is negative. Tangential velocity contributes no crossing.

import numpy as np

areas = np.array([0.01, 0.02])
normal_speeds = np.array([2.0, 1.0])
flow_rate = np.sum(areas * normal_speeds)
print(f"Outward volume flow: {flow_rate:.3f} m^3/s")

Average speed in a pipe

Real viscous pipe velocity is usually not uniform across the section. Define section- average normal speed by

\[\bar v=\frac{1}{A}\int_A\mathbf v\cdot\hat{\mathbf n}\,dA\]

Then \(Q=A\bar v\) is true by definition. It does not say every fluid parcel moves at \(\bar v\). In laminar circular pipe flow, for example, speed is zero at a no-slip wall and greatest at the center.

When comparing a measured centerline speed with a continuity calculation, convert it to the appropriate cross-sectional average first.

Mass flow rate

Mass crossing an oriented surface per time is

\[\dot m=\int_A\rho\mathbf v\cdot\hat{\mathbf n}\,dA\]

For uniform density and normal speed,

\[\dot m=\rho Av=\rho Q\]

Mass flow has SI units kilograms per second. In compressible flow, the same mass rate may cross two sections while volume rates differ because density changes.

The control-volume balance

For a fixed control volume, mass conservation says

\[\frac{d}{dt}\int_V\rho\,dV+\oint_A\rho\mathbf v\cdot\hat{\mathbf n}\,dA=0\]

The surface normal points outward. Positive surface flux is mass leaving, so it reduces stored mass. With separately named inlets and outlets this becomes

\[\frac{dM_{\mathrm{stored}}}{dt}=\sum\dot m_{\mathrm{in}}-\sum\dot m_{\mathrm{out}}\]
stored_mass, inlet, outlet, dt = 10.0, 2.0, 1.5, 0.1
next_mass = stored_mass + (inlet - outlet) * dt
print(f"Stored mass after step: {next_mass:.3f} kg")

A filling tank can have more inflow than outflow without violating continuity; its stored mass increases. Setting inflow equal to outflow silently assumes steady storage.

Steady one-streamtube flow

In steady flow, mass inside a fixed streamtube does not change. With one inlet and one outlet,

\[\rho_1A_1\bar v_1=\rho_2A_2\bar v_2\]

If density is also constant, it cancels:

\[A_1\bar v_1=A_2\bar v_2=Q\]

Therefore, halving area at fixed volume rate doubles average speed. This says nothing by itself about pressure; pressure-speed relations require momentum or energy equations and additional assumptions.

volume_flow, first_area, second_area = 0.02, 0.01, 0.005
first_speed, second_speed = volume_flow / first_area, volume_flow / second_area
assert np.isclose(first_area * first_speed, second_area * second_speed)
print("Speeds (m/s):", first_speed, second_speed)

Branches and junctions

At a steady incompressible junction with one inlet and several outlets,

\[Q_{\mathrm{in}}=\sum_k Q_{\mathrm{out},k}\]

Continuity determines only that sum. It does not determine how flow divides among branches. Pipe resistance, pressure boundary conditions, valves, pumps, and network momentum relations determine the split.

Use one sign convention throughout. With all section normals outward, inlet fluxes are negative and outlets positive, so a steady incompressible junction satisfies a zero signed sum.

Local continuity equation

Shrinking the control volume produces the differential form

\[\frac{\partial\rho}{\partial t}+\boldsymbol\nabla\cdot(\rho\mathbf v)=0\]

For a constant-density incompressible fluid,

\[\boldsymbol\nabla\cdot\mathbf v=0\]

Zero divergence does not require zero velocity or a uniform field. It means an infinitesimal material volume is not expanding or contracting.

In a finite-volume numerical method, one face flux should be shared by its two adjacent cells with opposite signs. This produces exact internal cancellation in the global mass ledger up to roundoff.

Compressible flow

For a gas passing through a nozzle, density, area, and velocity can all change. Steady one-dimensional mass conservation is

\[\rho Av=\text{constant}\]

A smaller area does not necessarily imply speed changes by the inverse area alone because density may also change. Near sonic conditions, pressure, temperature, and wave behavior couple through compressible-flow equations. The incompressible shortcut is then inadequate.

Liquids can often be approximated as incompressible over moderate pressure changes, but not universally. Density can also change through temperature, composition, or phase.

Moving boundaries and sources

If the control surface moves, flux must use fluid velocity relative to that surface. A moving piston can change stored volume even when no fluid crosses a sealed boundary. Phase change or chemical reaction does not create total mass, though a species balance can have production and consumption terms.

Leakage is another boundary flux, not unexplained loss. List every opening and source term explicitly before concluding that a result violates conservation.

Measurement and numerical checks

Flow meters have calibration and may report standard rather than actual gas volume rate. Area uncertainty can strongly affect inferred speed. A circular pipe area uses radius squared, so diameter errors propagate into area.

Check dimensions and signs at every section. Reconstruct mass rate from density, area, and average normal velocity. Sum all boundary rates and compare with measured or computed storage change. For a grid, refine resolution and compare integrated fluxes rather than only pointwise speed.

Test simple limits: zero velocity gives zero flux; tangential flow gives zero normal flux; reversing surface orientation reverses signed rate; halving area at steady constant density doubles average speed. These checks make continuity a verifiable ledger rather than a memorized pipe formula.

A worked interpretation

Suppose a steady stream of water passes from a broad section into a narrower section. The broad area is three times the narrow area. Because water density is treated as constant and no branch, leak, or storage lies between the sections, the same volume rate crosses each section. The narrow section's average speed is therefore three times the broad section's average speed. This conclusion follows from conservation before any pressure calculation is attempted.

Now imagine that the measured outlet rate is smaller than the inlet rate. Several explanations are possible. The region may be filling, fluid may leave through an unmeasured branch or leak, density may change, the measurements may refer to different time averages, or one instrument may be miscalibrated. Continuity does not authorize us to overwrite one measurement until the rates match. It tells us which additional ledger terms must be investigated.

For a pulsating flow, instantaneous inlet and outlet rates can differ even if their long-time averages match. A compliant pipe can temporarily store volume by expanding. Using only a steady formula would hide this behavior. Match the time window of all measurements and record whether the reported value is instantaneous, cycle-averaged, or long-time averaged.

Network bookkeeping

A pipe network can be represented by nodes and directed edges. Each edge carries a signed mass or volume rate. At a steady incompressible internal node with no storage, the sum of incoming rates equals the sum of outgoing rates. Boundary nodes supply or remove flow, and tanks carry storage state.

Continuity equations alone may leave many unknown edge rates. Pressure-loss relations and equipment curves supply the remaining equations. Keeping these roles separate is valuable: conservation determines which rates are compatible, while momentum and device models determine the actual distribution.

When a solver returns a network solution, calculate a residual at every node and a global boundary balance. Local residuals locate connection or sign mistakes that a global sum can hide through cancellation. Report residuals in the same flow-rate units as the solution, along with a scale-aware relative measure.

A worked Python notebook

Carry a steady volume flow of 0.02 cubic metres per second through different pipe areas. The question for this calculation is precise: how does mean flow speed change when we change pipe area, 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.

The simple continuity relation assumes incompressible flow without leakage. 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.005 to 0.02 m^2. 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 pipe area, expressed in m^2. The output is mean flow speed, expressed in m/s. 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{0.02}{q}\]

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 0.01 m^2, the expression gives 2 m/s. 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("0.02/q", locals={"q": q})
reference_input = 0.01
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "m^2")
print("Predicted mean flow speed:", reference_output, "m/s")

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 4 m/s. The midpoint, at 0.0125 m^2, gives 1.6 m/s. The upper endpoint gives 1 m/s. Read these together with the assumptions: they describe different choices of pipe area 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.005, 0.0125, 0.02])
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^2 -> {output_value:.6g} m/s")
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 pipe area; the vertical axis shows mean flow speed. 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.005, 0.02, 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("Pipe area (m^2)")
ax.set_ylabel("Mean flow speed (m/s)")
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 mean flow speed change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 0.01 m^2 is -200 in those ratio units. Locally, the output decreases 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{0.02}{q^{2}}\]

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 = 0.010075
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/s")
print("Full expression:", full_prediction, "m/s")
print("Approximation difference:", full_prediction - linear_prediction, "m/s")

Here the changed input is 0.010075 m^2. The tangent estimate is 1.985 m/s, while the full expression gives 1.98511 m/s. 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 = 0.015
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 pipe area inside the stated interval, predict whether mean flow speed 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: The simple continuity relation assumes incompressible flow without leakage. 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/s: 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(0.02) - evaluate(0.005))
for points in [101, 201, 401]:
    grid = np.linspace(0.005, 0.02, 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: