I want to solve u(x,t)=7.5-sin(x) numerically over the domain [0,2pi]. The problem has periodic boundary conditions u(0)=u(2pi)=7.5
I want to create a 1-D grid consisting of N grid cells where each grid cell contains some information X
and U
. For each cell, I've created pointers that point to the neighbour cells to connect the grid up, and since we have periodic boundary conditions I'd like to connect the first and last cell together.
A for loop is used to traverse the grid one cell at a time, and store the grid cells in a vector cells
.
I have a couple of problems here:
interp_u
andinterp_x
both return 0, it seems like they are using the initialised vectors with all values 0. How can I inputX
andU
forcell[i]
into the linear interpolated x and u?It's giving me a segmentation fault, I'm not too sure what the problem is.
Cheers!
class Grid {
public:
// Pointers to neighbour cells
Grid * LeftNeighbour;
Grid * RightNeighbour;
std::vector < double > X;
std::vector < double > U;
Grid() {
// Initialises vectors
std::vector < double > X(2);
std::vector < double > U(2);
}
double interp_x(double t) {
return X[0] * (1 / 2) * (1 - t) + X[1] * (1 / 2) * (1 + t);
}
double interp_u(double t) {
return U[0] * (1 / 2) * (1 - t) + U[1] * (1 / 2) * (1 + t);
}
};
int main() {
const long double pi = 3.1415926535897932384626433832795;
std::cout.precision(10);
int N = 5; //number of cells
std::vector < Grid > cells(N); //initialises vector of cells
Grid * RightNeighbour, * LeftNeighbour;
for (int i = 0; i < N; i++) {
cells[i].X[0] = 0 + ((2 * pi) / N) * i;
cells[i].X[1] = cells[i].X[0] + ((2 * pi) / N); //SEGMENTATION FAULT
cells[i].U[0] = 7.5 - sin(cells[i].X[0]);
cells[i].U[1] = 7.5 - sin(cells[i].X[1]);
std::cout << "u(t=0) = " << cells[i].interp_u(0) << std::endl; //linear interpolation
if (i == 0) { //first cell
LeftNeighbour = & cells[N - 1];
RightNeighbour = & cells[i + 1];
}
if ((i % (N - 1)) != 0) {
LeftNeighbour = & cells[i - 1];
RightNeighbour = & cells[i + 1];
}
if (i == N - 1) { //last cell
LeftNeighbour = & cells[i - 1];
RightNeighbour = & cells[0];
}
}
return 0;
}