1D Heat Equation Solver 1.0
Computational Methods Assignment 2025
Loading...
Searching...
No Matches
grid.cpp
Go to the documentation of this file.
1/**
2 * @file grid.cpp
3 * @brief Implementation of the uniform 1D grid and its validator.
4 */
5
6#include "grid.hpp"
7#include <cmath>
8#include <stdexcept>
9#include <cassert>
10
11Grid::Grid(double L_cm, double dx_cm) : L(L_cm), dx(dx_cm) {
12 if (L <= 0.0 || dx <= 0.0) {
13 throw std::invalid_argument("Grid: L and dx must be positive.");
14 }
15 // Nx = round(L/dx) + 1 to include both endpoints 0 and L
16 Nx = static_cast<std::size_t>(std::llround(L / dx)) + 1;
17 if (Nx < 2) {
18 throw std::invalid_argument("Grid: Nx < 2 (check L and dx).");
19 }
20 x.resize(Nx);
21 for (std::size_t i = 0; i < Nx; ++i) {
22 x[i] = static_cast<double>(i) * dx;
23 }
24}
25
26bool validate_grid(const Grid& g, double tol) {
27 assert(g.Nx >= 2);
28
29 // 1) Endpoints at 0 and ~L
30 assert(std::fabs(g.x.front() - 0.0) <= tol);
31 assert(std::fabs(g.x.back() - g.L) <= tol);
32
33 // 2) Monotonic non-decreasing
34 for (std::size_t i = 1; i < g.Nx; ++i) {
35 assert(g.x[i] >= g.x[i-1]);
36 }
37
38 // 3) Uniform spacing: x[i] - x[i-1] ≈ dx
39 for (std::size_t i = 1; i < g.Nx; ++i) {
40 const double step = g.x[i] - g.x[i-1];
41 assert(std::fabs(step - g.dx) <= tol);
42 }
43
44 // 4) Consistency with construction rule: Nx == round(L/dx) + 1
45 const std::size_t idxL = static_cast<std::size_t>(std::llround(g.L / g.dx));
46 assert(idxL + 1 == g.Nx);
47
48 return true;
49}
bool validate_grid(const Grid &g, double tol)
Validate grid consistency (assertions in Debug mode).
Definition grid.cpp:26
Uniform 1D spatial grid.
Uniform 1D grid on x ∈ [0, L], including both boundary nodes.
Definition grid.hpp:15
std::size_t Nx
Number of nodes (including boundaries).
Definition grid.hpp:18
double dx
Spatial step [cm].
Definition grid.hpp:17
std::vector< double > x
Node coordinates [cm].
Definition grid.hpp:19
double L
Domain length [cm].
Definition grid.hpp:16
Grid(double L_cm, double dx_cm)
Construct a grid with given length and spacing.
Definition grid.cpp:11