[Codewars] Euler`s method for a first-order ODE

Euler’s method for a first-order ODE

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <bits/stdc++.h>
using namespace std;
class EulerOde
{
public:
static double exact_sol(double t){
return 1.0 + 0.5*std::exp(-4.0*t) - 0.5*std::exp(-2.0*t);
}

static double f(double y, double t){
return 2.0 - std::exp(-4.0*t) - 2.0*y;
}

static double exEuler(int nb){

double y = 1, t = 0, h = 1. / nb;
double error = std::fabs(y - exact_sol(t))/exact_sol(t);

for(int i=0; i < nb; i++){
y += f(y,t)*h;
t += h;
error += std::fabs(y - exact_sol(t))/exact_sol(t);
}

return std::trunc((error/(nb+1.0f))*1e6f)/1e6f;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/07/PS/Codewars/eulers-method-for-a-first-order-ode/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.