Skip to content

Instantly share code, notes, and snippets.

@danielkelshaw
Created October 9, 2020 11:06
Show Gist options
  • Save danielkelshaw/06861688c2a95e61fe456e664f8edb6a to your computer and use it in GitHub Desktop.
Save danielkelshaw/06861688c2a95e61fe456e664f8edb6a to your computer and use it in GitHub Desktop.

Basic example of using C++ for a HT simulation.

#ifndef INPUT_H
#define INPUT_H
#include <iostream>
#include <fstream>
#include <cmath>
// User Constants
const double radius = 1.2e-2;
const double density = 8800.0;
const double specific_heat = 400.0;
const double initial_temperature = 800.0;
const double atmospheric_temperature = 15.0;
// Universal Constants
const double sigma = 5.67e-8;
// Programamatic Constants
const double t_simulation = 30.0 * 60.0;
const double t_step = 1e-2;
const int n_steps = static_cast<int>(std::round(t_simulation / t_step));
const int t_logging = n_steps / 10000;
// Macros
#define SQ(x) ((x) * (x))
#define CU(x) ((x) * (x) * (x))
#define QU(x) ((x) * (x) * (x) * (x))
#endif
#include "./input.h"
#include "./problem.h"
int main() {
std::cout << "HT Simulation Test..." << std::endl;
Problem prob(initial_temperature);
for (prob.time_step = 1; prob.time_step < n_steps; prob.time_step++) {
prob.calc_temperature();
if (prob.time_step % t_logging == 0) {
prob.write_file();
}
}
std::cout << "Simulation Finished..." << std::endl;
return 0;
}
#include "./input.h"
#include "./problem.h"
void Problem::calc_temperature() {
update_gradient();
temperature = temperature - temperature_grad * t_step;
}
void Problem::write_file() {
std::ofstream output;
output.precision(10);
output.open("results.csv", std::ios::out | std::ios::app);
output << time_step * t_step << ", " << temperature << ", " << temperature_grad << "\n";
output.close();
}
void Problem::update_gradient() {
temperature_grad = 3.0 * (sigma / (radius * density * specific_heat)) * (QU(temperature) - QU(atmospheric_temperature));
}
// Custom Constructor
Problem::Problem(double initial_temp) {
std::cout << "Initialising Problem..." << std::endl;;
time_step = 0;
temperature = initial_temp;
}
// Defaul Constructor
Problem::Problem() {
std::cout << "Initialising Problem..." << std::endl;
time_step = 0;
temperature = 100.0;
}
#ifndef PROBLEM_H
#define PROBLEM_H
class Problem {
public: // con/de-structors
Problem();
~Problem() {};
Problem(double initial_temp);
public: // attributes
int time_step;
double temperature;
double temperature_grad;
private: // attributes
public: // methods
void calc_temperature();
void write_file();
private: // methods
void update_gradient();
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment