Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

#include <iostream>

#include <fstream>
#include <vector>
#include <string>
#include <chrono>

class HeatSolver {
public:
HeatSolver(double length, int divisions, int iterations)
: L(length), n(divisions), numIterations(iterations) {
dx = L / (n - 1);
temperature = std::vector<std::vector<double>>(n, std::vector<double>(n, 0.0));
}

void run() {
initializeTemperature();
exportToVTK("initial_temperature.vtk");

auto start_time = std::chrono::high_resolution_clock::now();

for (int iter = 0; iter < numIterations; ++iter) {


laplaceIteration();
}

auto end_time = std::chrono::high_resolution_clock::now();


auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);

exportToVTK("final_temperature.vtk");

std::cout << "Time taken: " << duration.count() / 1000.0 << " seconds" << std::endl;
}

private:
double L; // length
int n; // divisions of the domain
int numIterations;
double dx;
std::vector<std::vector<double>> temperature;

void initializeTemperature() {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
temperature[i][j] = 300.0;
}
}

for (int j = 0; j < n; ++j) {


temperature[n - 1][j] = 1000.0;
}
}

void exportToVTK(const std::string& filename) {


std::ofstream vtkFile(filename.c_str());

vtkFile << "# vtk DataFile Version 3.0" << std::endl;


vtkFile << "Temperature Field" << std::endl;
vtkFile << "ASCII" << std::endl;
vtkFile << "DATASET STRUCTURED_GRID" << std::endl;
vtkFile << "DIMENSIONS " << n << " " << n << " 1" << std::endl;
vtkFile << "POINTS " << n * n << " float" << std::endl;

// criar os pontos de malha


const double dx = L / (n - 1);

for (int i = 0; i < n; ++i) {


for (int j = 0; j < n; ++j) {
vtkFile << i * dx << " " << j * dx << " 0" << std::endl;
}
}

// exportar os valores de temperatura


vtkFile << "POINT_DATA " << n * n << std::endl;
vtkFile << "SCALARS Temperature float" << std::endl;
vtkFile << "LOOKUP_TABLE default" << std::endl;

for (int i = 0; i < n; ++i) {


for (int j = 0; j < n; ++j) {
vtkFile << temperature[i][j] << " ";
}
}

vtkFile.close();

void laplaceIteration() {
for (int i = 1; i < n - 1; ++i) {
for (int j = 1; j < n - 1; ++j) {
temperature[i][j] = 0.25 * (temperature[i + 1][j] + temperature[i - 1][j] +
temperature[i][j + 1] + temperature[i][j - 1]);
}
}
}
};

int main() {
HeatSolver solver(1.0, 100, 1000);
solver.run();

// Optionally, you can call another C++ program here using the methods described earlier.

return 0;
}

You might also like