Numerical methods code
Numerical methods code
Purpose
Write solution code for a numerical methods or heat transfer assignment: solve a differential equation by finite differences (FDM), check it against the exact solution and a conserved quantity, and show the error falling at the theoretical order as the grid is refined. Output: LaTeX tables, a number file and PDF figures ready for the report.
The AI does not invent property values or exact solutions. If the observed order differs from theory, it never writes as if it matched; it finds which boundary or equation loses order and says so.
Input
- Required: the problem (governing equation, boundary conditions, properties and geometry). If missing, ask only: "Please send the equation, boundary conditions and property values of the problem."
- Helpful: required method, language (Python or MATLAB), grid sizes, tolerance, format, code skeleton.
- If your school or instructor gave you a template, code skeleton, function names or output format, that comes first. For MATLAB, split the same structure into .m function files.
- No exact solution: use a very fine grid or Richardson extrapolation as the reference, and say so.
- Property values without a source are used but tagged `[source needed]`. Never edit values or text the user marked "keep as is".
Output
1. `fin_fdm.py`, `results/` (`table_convergence.tex`, `values.tex`, `results.md`, `fig_profile.pdf/.png`, `fig_convergence.pdf/.png`), and `preview.tex` with its PDF, showing them in a report.
2. In the chat, "Points to check", 3–7 lines: max error and observed order, boundary treatment, energy imbalance, property sources, whether it compiled and actually ran.
3. If code cannot run here, label the files "not run yet". Never guess error or order numbers.
Rules
1. Steps
1) Write the governing equation, boundary conditions, unknowns and units one per line, with the dimensionless groups (mL, grid Biot number hΔx/k).
2) Write the discrete equation for each node type: interior, x = 0, x = L. Mark the accuracy order of each boundary equation.
3) Separate building coefficients from solving. Check a hand-written solver against `numpy.linalg.solve`.
4) Compare with exact, halve the grid, compute the order, check the energy balance.
5) Make tables, figures and numbers, place them with `preview.tex`, run section 9.
2. Functions and names
- One job per function, under 30 lines. Docstring with units: "Returns node positions x (m) and θ (K), N+1 values each."
- Compute in SI (m, W, K). mm and °C only in tables and figures.
- No magic numbers: properties in one `dataclass`, grids and options as upper-case constants.
- Names follow the equation symbols (`theta_b`, `A_c`, `Bi`), one name per quantity.
3. Verification
- Max error max|θ_FDM − θ_exact| for every grid.
- Observed order p = log2(e(2Δx) / e(Δx)). Second-order central differences must land in 1.9–2.1.
- The boundary equation sets the overall order. A first-order one-sided tip condition gives p = 1 even with second-order interior nodes. A ghost node (θ_{N+1}) keeps second order.
- Energy balance: heat in at the base (second-order one-sided gradient) against heat out by convection (side by trapezoid rule, plus tip). Halving the grid should cut the gap to about 1/4. A first-order base gradient (θ0 − θ1)/Δx leaves a gap proportional to Δx.
- Error rising again near 10⁻¹⁰ on very fine grids is round-off: leave those grids out and say so.
4. Grid convergence study
- Halve the spacing: N = 4, 8, 16, 32, 64, 128. Five steps or more.
- Log-log plot: x axis Δx (mm), y axis max error (K). Slope 1 and 2 guides as grey dashed lines; label the finest point with its p.
- Tick labels are the actual spacings (0.3125, 0.625 …), not powers of ten.
5. Figures
- Axis labels with quantity and unit: "Position x (mm)", "Temperature T (°C)", "FDM − exact (K)".
- Exact as a line, FDM as open markers; two boundary treatments differ in marker and color.
- Panels titled (a), (b), referred to in the caption. PDF for the report, PNG 200 dpi for slides.
6. Tables and numbers in the report
- `booktabs` three-rule table. Columns: N, Δx (mm), max error (K), observed order p, q_f (W), q_f error (%), imbalance (%).
- Digits: errors in 3 significant figures with exponent (`\num{1.15e-02}`), p with 2 decimals, q_f with 4.
- The first row's p is "---" because there is no coarser grid. The caption defines p and imbalance.
- Text numbers come only from names in the generated `values.tex` (`\qExact`, `\pGhost`); the tabular is a generated file, `\input` in the table.
7. Sentences (before → after)
- "As the number of grid points increased, the error decreased, confirming the accuracy of the numerical solution." → "Each halving of the grid spacing cut the max error to 1/4 (observed order p = 2.00, N = 8 to 128), the theoretical order 2 of central differences."
- "The tip boundary condition was treated with a backward difference." → "With a first-order backward difference at the tip, the observed order fell to 1.00 and the q_f error at N = 4 was −10.9 %. A ghost node restored second order."
- "Energy conservation is well satisfied." → "The gap between heat in at the base and heat out by convection fell with the grid, from −0.85 % at N = 4 to −0.0009 % at N = 128."
8. The two files
Both files were run and compiled end to end on a hypothetical case: an aluminium heat sink fin (k = 180 W/(m·K), h = 25 W/(m²·K), L = 40 mm, 1.5 × 30 mm section, base 80 °C, air 25 °C). The values were set for the example, not taken from a product; a real assignment cites textbook or data sheet values.
- `fin_fdm.py`: run `python fin_fdm.py` (numpy, matplotlib). In this case the observed order was 2.00 with the ghost node and 1.00 one-sided, and the exact q_f = 3.191 W. For another problem, change `Fin`, `fdm_system` and the exact-solution functions.
- `preview.tex`: one-page sample of the results in a report. Run `pdflatex preview.tex` twice; standard packages only, so Overleaf's default pdfLaTeX works (upload `results/` too).
9. Final check
- Equation, boundary conditions and units match the docstring at the top of the code.
- The `thomas` cross-check `assert` passed.
- Observed order within 0.1 of theory. If not, the boundary equation responsible was found.
- Energy imbalance shrinks with the grid.
- No hand-typed result numbers in text or tables.
- Axes have units, the log plot has guides, the compile log has no errors or `Overfull`.
- You said whether you actually ran and compiled, or only wrote the files.
Attachment 1 · fin_fdm.py (Python)
```python
"""fin_fdm.py - 1D steady conduction in a rectangular fin by finite differences (FDM), checked against exact.
Equation d²θ/dx² − m²θ = 0, θ = T − T∞, m² = hP/(kA_c)
Bounds x = 0: θ = θ_b x = L: −k dθ/dx = hθ (tip convection)
Run python fin_fdm.py → results/: tables (results.md, table_convergence.tex), numbers (values.tex),
figures (PDF and PNG)
Units SI (m, W, K) in all calculations; mm and °C only in tables and figures.
"""
from dataclasses import dataclass
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
GRIDS = [4, 8, 16, 32, 64, 128] # number of intervals N; spacing halves each step
N_SHOW = 8 # grid shown as markers in the profile figure
OUT = Path("results")
@dataclass(frozen=True)
class Fin:
"""Fin and surroundings. Defaults are the hypothetical case (aluminium heat sink fin), all SI."""
k: float = 180.0 # thermal conductivity (W/(m·K))
h: float = 25.0 # convection coefficient (W/(m²·K))
L: float = 0.040 # fin length (m)
t: float = 0.0015 # thickness (m)
w: float = 0.030 # width (m)
T_b: float = 80.0 # base temperature (°C)
T_inf: float = 25.0 # ambient air temperature (°C)
@property
def A_c(self): # cross-section area (m²)
return self.w * self.t
@property
def P(self): # perimeter (m)
return 2 * (self.w + self.t)
@property
def m(self): # fin parameter (1/m)
return np.sqrt(self.h * self.P / (self.k * self.A_c))
@property
def theta_b(self): # base excess temperature (K)
return self.T_b - self.T_inf
def exact_theta(fin, x):
"""Exact θ(x) (K). x: positions (m)."""
r, mL = fin.h / (fin.m * fin.k), fin.m * fin.L
num = np.cosh(fin.m * (fin.L - x)) + r * np.sinh(fin.m * (fin.L - x))
return fin.theta_b * num / (np.cosh(mL) + r * np.sinh(mL))
def exact_q(fin):
"""Exact fin heat rate q_f (W)."""
r, mL = fin.h / (fin.m * fin.k), fin.m * fin.L
M = np.sqrt(fin.h * fin.P * fin.k * fin.A_c) * fin.theta_b
return M * (np.sinh(mL) + r * np.cosh(mL)) / (np.cosh(mL) + r * np.sinh(mL))
def thomas(a, b, c, d):
"""Tridiagonal solve. a: lower (a[0] unused), b: main, c: upper (c[-1] unused), d: right side."""
n = len(d)
cp, dp = np.zeros(n), np.zeros(n)
cp[0], dp[0] = c[0] / b[0], d[0] / b[0]
for i in range(1, n):
den = b[i] - a[i] * cp[i - 1]
cp[i] = c[i] / den if i < n - 1 else 0.0
dp[i] = (d[i] - a[i] * dp[i - 1]) / den
x = np.zeros(n)
x[-1] = dp[-1]
for i in range(n - 2, -1, -1):
x[i] = dp[i] - cp[i] * x[i + 1]
return x
def fdm_system(fin, N, tip):
"""FDM coefficients (a, b, c, d). N: intervals; tip: "ghost" (ghost node, 2nd order) or "onesided" (1st)."""
dx = fin.L / N
Bi = fin.h * dx / fin.k # grid Biot number (dimensionless)
a, c, d = np.ones(N + 1), np.ones(N + 1), np.zeros(N + 1)
b = np.full(N + 1, -(2 + (fin.m * dx) ** 2))
b[0], c[0], d[0] = 1.0, 0.0, fin.theta_b # x = 0: θ = θ_b
if tip == "ghost": # substitute θ_{N+1} = θ_{N−1} − 2Bi·θ_N: 2θ_{N−1} − (2 + (mΔx)² + 2Bi)θ_N = 0
a[N], b[N] = 2.0, -(2 + (fin.m * dx) ** 2 + 2 * Bi)
else: # −k(θ_N − θ_{N−1})/Δx = hθ_N: θ_{N−1} − (1 + Bi)θ_N = 0
a[N], b[N] = 1.0, -(1 + Bi)
return a, b, c, d
def solve_fdm(fin, N, tip="ghost"):
"""FDM solution. Returns node positions x (m) and θ (K), N+1 values each."""
return np.linspace(0, fin.L, N + 1), thomas(*fdm_system(fin, N, tip))
def heat_balance(fin, x, th):
"""Energy balance (W). q_in: base conduction (2nd-order one-sided), q_out: side (trapezoid) + tip."""
dx = x[1] - x[0]
q_in = -fin.k * fin.A_c * (-3 * th[0] + 4 * th[1] - th[2]) / (2 * dx)
q_out = fin.h * fin.P * dx * (th.sum() - (th[0] + th[-1]) / 2) + fin.h * fin.A_c * th[-1]
return q_in, q_out
def convergence(fin, tip):
"""Per grid: max error (K), observed order, heat rate (W) and its error (%), energy imbalance (%)."""
rows = []
for N in GRIDS:
x, th = solve_fdm(fin, N, tip)
q_in, q_out = heat_balance(fin, x, th)
rows.append({"N": N, "dx_mm": fin.L / N * 1e3, "err_K": np.abs(th - exact_theta(fin, x)).max(),
"q_W": q_in, "q_err": (q_in / exact_q(fin) - 1) * 100, "imb": (q_in - q_out) / q_in * 100})
for prev, row in zip(rows, rows[1:]): # by what factor does the error drop when Δx halves?
row["p"] = np.log2(prev["err_K"] / row["err_K"])
return rows
def check_solver(fin, N=16):
"""Compare the hand-written thomas with numpy.linalg.solve. Raises AssertionError if they differ."""
a, b, c, d = fdm_system(fin, N, "ghost")
A = np.diag(b) + np.diag(a[1:], -1) + np.diag(c[:-1], 1)
assert np.allclose(thomas(a, b, c, d), np.linalg.solve(A, d), rtol=1e-12, atol=1e-12)
def summary(fin):
"""Fin performance from the exact solution: q_f (W), efficiency (tip area included), effectiveness, T_tip (°C)."""
q = exact_q(fin)
eta = q / (fin.h * (fin.P * fin.L + fin.A_c) * fin.theta_b)
eps = q / (fin.h * fin.A_c * fin.theta_b)
return q, eta, eps, fin.T_inf + exact_theta(fin, np.array([fin.L]))[0]
def set_style():
"""Figure style: one font that has every glyph used (θ, Δ, °, −)."""
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 9, "savefig.dpi": 200, "axes.grid": True,
"grid.color": "#e7e7e7", "axes.spines.top": False, "axes.spines.right": False})
MARK = {"ghost": ("o", "#257de0", "tip: ghost node (2nd order)"),
"onesided": ("^", "#f47230", "tip: one-sided (1st order)")}
def plot_profile(fin):
"""(a) Temperature T(x) and (b) difference from exact, N = N_SHOW. results/fig_profile.pdf and .png."""
xs = np.linspace(0, fin.L, 200)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7.2, 2.9))
ax1.plot(xs * 1e3, fin.T_inf + exact_theta(fin, xs), color="#191919", lw=1.4, label="exact")
for tip, (mk, col, lab) in MARK.items():
x, th = solve_fdm(fin, N_SHOW, tip)
ax1.plot(x * 1e3, fin.T_inf + th, mk, ms=5, mfc="none", color=col, label=f"FDM N = {N_SHOW}, {lab}")
ax2.plot(x * 1e3, th - exact_theta(fin, x), mk + "-", ms=4, mfc="none", color=col, lw=1)
ax1.set(xlabel="Position x (mm)", ylabel="Temperature T (°C)")
ax2.set(xlabel="Position x (mm)", ylabel="FDM − exact (K)")
ax1.set_title("(a) Temperature profile", loc="left", fontsize=9)
ax2.set_title("(b) Difference from exact", loc="left", fontsize=9)
ax1.legend(frameon=False, fontsize=7)
fig.tight_layout()
for ext in ("pdf", "png"):
fig.savefig(OUT / f"fig_profile.{ext}")
def plot_convergence(res):
"""Log-log grid spacing vs max error with slope 1 and 2 guides. results/fig_convergence.pdf and .png."""
fig, ax = plt.subplots(figsize=(4.2, 3.2))
for tip, (mk, col, lab) in MARK.items():
h = np.array([r["dx_mm"] for r in res[tip]])
e = np.array([r["err_K"] for r in res[tip]])
ax.loglog(h, e, mk + "-", ms=5, mfc="none", color=col, lw=1.2, label=lab)
ax.annotate(f"p = {res[tip][-1]['p']:.2f}", (h[-1], e[-1]), xytext=(4, -10), textcoords="offset points")
for p, y0 in [(2, 3e-4), (1, 2e-2)]: # guide heights chosen to stay clear of the data
ax.loglog(h[[0, -1]], y0 * (h[[0, -1]] / h[0]) ** p, color="#9c9c9c", lw=0.8, ls="--")
ax.annotate(f"slope {p}", (h[0], y0), xytext=(-8, 4), textcoords="offset points", ha="right", color="#666666")
ax.set(xlabel="Grid spacing Δx (mm)", ylabel="Max error (K)")
ax.set_xticks(h, [f"{v:g}" for v in h])
ax.minorticks_off()
ax.legend(frameon=False, fontsize=7, loc="lower right")
fig.tight_layout()
for ext in ("pdf", "png"):
fig.savefig(OUT / f"fig_convergence.{ext}")
def write_tables(fin, res):
"""Report table (table_convergence.tex, booktabs), numbers (values.tex), summary (results.md)."""
q_ex, eta, eps, T_tip = summary(fin)
tex = ["\\begin{tabular}{rrrrrrr}", "\\toprule",
"$N$ & $\\Delta x$ (mm) & Max error (K) & Order $p$ & "
"$q_f$ (W) & $q_f$ error (\\%) & Imbalance (\\%) \\\\",
"\\midrule"]
md = ["| N | Δx (mm) | Max error (K) | Order p | q_f (W) | q_f error (%) | Imbalance (%) |",
"|---:|---:|---:|---:|---:|---:|---:|"]
for r in res["ghost"]: # first row has no coarser grid to compare: p is '—'
cells = [f"{r['N']}", f"{r['dx_mm']:g}", f"{r['err_K']:.2e}", f"{r['p']:.2f}" if "p" in r else "—",
f"{r['q_W']:.4f}", f"{r['q_err']:+.4f}", f"{r['imb']:+.4f}"]
md.append("| " + " | ".join(cells) + " |")
tex.append(" & ".join(cells[:2] + ["---" if v == "—" else f"\\num{{{v}}}" for v in cells[2:]]) + " \\\\")
tex += ["\\bottomrule", "\\end{tabular}"]
(OUT / "table_convergence.tex").write_text("\n".join(tex) + "\n", encoding="utf-8")
one = res["onesided"]
vals = {"finK": f"{fin.k:g}", "finH": f"{fin.h:g}", "finL": f"{fin.L * 1e3:g}", "qExact": f"{q_ex:.3f}",
"etaFin": f"{eta:.3f}", "Ttip": f"{T_tip:.2f}", "pGhost": f"{res['ghost'][-1]['p']:.2f}",
"pOne": f"{one[-1]['p']:.2f}", "qErrOne": f"{one[0]['q_err']:.1f}", "Nmin": f"{GRIDS[0]}"}
(OUT / "values.tex").write_text("".join(f"\\newcommand{{\\{k}}}{{{v}}}\n" for k, v in vals.items()),
encoding="utf-8") # the report text calls numbers by these names only
(OUT / "results.md").write_text("\n".join([
f"# Fin FDM check (hypothetical case: k = {fin.k:g} W/(m·K), h = {fin.h:g} W/(m²·K), L = {fin.L * 1e3:g} mm)",
"", f"- Exact: q_f = {q_ex:.4f} W, tip {T_tip:.2f} °C, efficiency {eta:.3f}, effectiveness {eps:.1f}",
f"- One-sided (1st order) tip: observed p = {one[-1]['p']:.2f}, q_f error {one[0]['q_err']:+.2f} % "
f"at N = {GRIDS[0]}, {one[-1]['q_err']:+.2f} % at N = {GRIDS[-1]}", "",
"Table 1. Grid convergence (tip: ghost node). Imbalance = (q_in − q_out)/q_in", "", *md, ""]),
encoding="utf-8")
def main():
fin = Fin()
OUT.mkdir(exist_ok=True)
check_solver(fin)
res = {tip: convergence(fin, tip) for tip in ("ghost", "onesided")}
set_style()
plot_profile(fin)
plot_convergence(res)
write_tables(fin, res)
q_ex, eta, eps, _ = summary(fin)
g, o = res["ghost"][-1], res["onesided"][-1]
print(f"m = {fin.m:.4f} 1/m, mL = {fin.m * fin.L:.4f}, "
f"q_f (exact) = {q_ex:.4f} W, efficiency {eta:.3f}, effectiveness {eps:.1f}")
print(f"ghost node N = {g['N']}: max error {g['err_K']:.2e} K, p = {g['p']:.2f}, imbalance {g['imb']:+.4f} %")
print(f"one-sided N = {o['N']}: max error {o['err_K']:.2e} K, p = {o['p']:.2f}, imbalance {o['imb']:+.4f} %")
if __name__ == "__main__":
main()
```
Attachment 2 · preview.tex (LaTeX)
```latex
% preview.tex - one-page sample showing how the tables, figures and numbers from fin_fdm.py sit in a report
% Compile: python fin_fdm.py, then pdflatex preview.tex twice (Overleaf: upload results/ as a folder; default pdfLaTeX)
\documentclass[11pt,a4paper]{article}
\usepackage[margin=22mm]{geometry}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{amsmath,graphicx,booktabs,siunitx,caption,float}
\sisetup{exponent-product=\times}
\captionsetup{font=small,labelfont=bf}
\input{results/values.tex}
\begin{document}
\section*{4. Results: verifying the finite-difference solution}
The aluminium fin of the hypothetical case ($k=\SI{\finK}{W/(m.K)}$, $h=\SI{\finH}{W/(m^2.K)}$,
$L=\SI{\finL}{mm}$) was solved with second-order central differences. A ghost node keeps the tip
boundary second-order as well. The exact solution gives a heat rate of $q_f=\SI{\qExact}{W}$, a tip
temperature of \SI{\Ttip}{\degreeCelsius} and a fin efficiency of \etaFin. Figure~\ref{fig:profile}
shows the solution for $N=8$; Table~\ref{tab:conv} and Figure~\ref{fig:conv} show grid convergence.
\begin{figure}[H]\centering
\includegraphics[width=0.94\linewidth]{results/fig_profile.pdf}
\caption{Finite-difference solution for $N=8$, shown with a one-sided (first-order) tip boundary.}\label{fig:profile}
\end{figure}
\begin{table}[H]\centering\small
\caption{Grid convergence (tip: ghost node). $p=\log_2(e_{2\Delta x}/e_{\Delta x})$,
imbalance $=(q_\text{in}-q_\text{out})/q_\text{in}$.}\label{tab:conv}
\input{results/table_convergence.tex}
\end{table}
\begin{figure}[H]\centering
\includegraphics[width=0.52\linewidth]{results/fig_convergence.pdf}
\caption{Maximum error against grid spacing. Dashed lines: slope 1 and 2 guides.}\label{fig:conv}
\end{figure}
Observed order: ghost node $p=\pGhost$, one-sided $p=\pOne$. With the one-sided tip, the $q_f$ error
at $N=\Nmin$ was \SI{\qErrOne}{\percent}.
\end{document}
```
Connect ChatGPT or Claude and use this prompt now · More prompts