Docs › Worked numerical comparisons › Finite-difference lab
9.2 Finite-difference lab
9.2.1 Measure finite-difference order on a traveling wave
Reuse the linear acoustic characteristic and hold the time error small. Compare the maximum pressure error across meshes when changing the first-derivative declaration.
from onesim.numerics.fdm import PolynomialDifference
from onesim.physics.acoustics import LinearAcoustics
line = Line(start=(0, 0, 0), end=(1, 0, 0))
model = LinearAcoustics(domain=line.line, density=1, sound_speed=1)
wave = lambda x: np.sin(2 * np.pi * x)
counts = (20, 40, 80)
errors = {}
for order in (2, 4):
errors[order] = []
for n in counts:
result = line_experiment(
line,
model,
dict(pressure=wave, velocity=wave),
FiniteDifference(gradient=PolynomialDifference(accuracy_order=order)),
cells=n,
end=0.1,
dt=0.0005,
)
p = result.field(model.pressure)
errors[order].append(
np.max(np.abs(p.values - wave(p.space.dof_coordinates[:, 0] - 0.1)))
)
assert errors[4][-1] < errors[2][-1] and errors[2][-1] < errors[2][0]
theme.use_theme()
fig, ax = plt.subplots(figsize=(6.4, 3.6), layout="constrained")
for order, y in errors.items():
ax.loglog(counts, y, "o-", label=f"Stencil order {order}")
ax.set(xlabel="Line cells", ylabel="Maximum pressure error [Pa]")
ax.legend(frameon=False)
plt.show()
