54void problem(
const double &x, std::valarray<double> *y,
55 std::valarray<double> *dy) {
56 const double omega = 1.F;
58 (*dy)[1] = -omega * omega * (*y)[0];
68 y[0][0] = std::cos(x);
69 y[0][1] = -std::sin(x);
87 std::valarray<double> *y, std::valarray<double> *dy) {
103 std::valarray<double> *y,
bool save_to_file =
false) {
104 std::valarray<double> dy = *y;
108 fp.open(
"forward_euler.csv", std::ofstream::out);
110 std::perror(
"Error! ");
114 std::size_t L = y->size();
117 std::clock_t t1 = std::clock();
121 if (save_to_file && fp.is_open()) {
124 for (
int i = 0; i < L - 1; i++) {
125 fp << y[0][i] <<
",";
127 fp << y[0][L - 1] <<
"\n";
132 }
while (x <= x_max);
134 std::clock_t t2 = std::clock();
140 return static_cast<double>(t2 - t1) / CLOCKS_PER_SEC;
154 const double &step_size,
155 const std::valarray<double> &Y0) {
157 std::valarray<double> y(Y0);
159 std::ofstream fp(
"exact.csv", std::ostream::out);
161 std::perror(
"Error! ");
164 std::cout <<
"Finding exact solution\n";
166 std::clock_t t1 = std::clock();
169 for (
int i = 0; i < y.size() - 1; i++) {
172 fp << y[y.size() - 1] <<
"\n";
177 }
while (x <= X_MAX);
179 std::clock_t t2 = std::clock();
180 double total_time =
static_cast<double>(t2 - t1) / CLOCKS_PER_SEC;
181 std::cout <<
"\tTime = " << total_time <<
" ms\n";
189int main(
int argc,
char *argv[]) {
192 std::valarray<double> Y0{1.f, 0.f};
193 double step_size = NAN;
196 std::cout <<
"\nEnter the step size: ";
197 std::cin >> step_size;
200 step_size = std::atof(argv[1]);
204 double total_time =
forward_euler(step_size, X0, X_MAX, &Y0,
true);
205 std::cout <<
"\tTime = " << total_time <<
" ms\n";
void forward_euler_step(const double dx, const double x, std::valarray< double > *y, std::valarray< double > *dy)
Compute next step approximation using the forward-Euler method.
double forward_euler(double dx, double x0, double x_max, std::valarray< double > *y, bool save_to_file=false)
Compute approximation using the forward-Euler method in the given limits.
void save_exact_solution(const double &X0, const double &X_MAX, const double &step_size, const std::valarray< double > &Y0)
void problem(const double &x, std::valarray< double > *y, std::valarray< double > *dy)
Problem statement for a system with first-order differential equations. Updates the system differenti...
void exact_solution(const double &x, std::valarray< double > *y)
Exact solution of the problem. Used for solution comparison.