Skip to content

Commit 71a0842

Browse files
committed
Added forward euler in js, fixed ODE
1 parent 057dd6d commit 71a0842

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
function solveEuler(timeStep, n){
2+
const result=[];
3+
if (n != 0) {
4+
result[0] = 1;
5+
for (let i = 1; i < n; ++i) {
6+
result[i] = result[i-1] - 3 * result[i-1] * timeStep;
7+
}
8+
}
9+
return result;
10+
}
11+
12+
function checkResult(result, threshold, timeStep) {
13+
let approx = true;
14+
for (let i = 0; i < result.length; ++i){
15+
const solution = Math.exp(-3 * i * timeStep);
16+
if (Math.abs(result[i] - solution) > threshold) {
17+
console.log(result[i]+" "+solution);
18+
approx = false;
19+
}
20+
}
21+
return approx;
22+
}
23+
24+
const timeStep = 0.01;
25+
const n = 100;
26+
const threshold = 0.01;
27+
28+
const result = solveEuler(timeStep, n)
29+
const approx = checkResult(result, threshold, timeStep)
30+
31+
if (approx) {
32+
console.log("All values within threshold");
33+
}else{
34+
console.log("Value(s) not in threshold");
35+
}

contents/forward_euler_method/forward_euler_method.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ That said, variations of this method *are* certainly used (for example Crank-Nic
9595

9696
Like in the case of [Verlet Integration](../verlet_integration/verlet_integration.md), the easiest way to test to see if this method works is to test it against a simple test-case.
9797
Here, the most obvious test-case would be dropping a ball from 5 meters, which is my favorite example, but proved itself to be slightly less enlightening than I would have thought.
98-
So, this time, let's remove ourselves from any physics and instead solve the following ODE: $$y(t)' = -3t$$ with the initial condition that $$y(0) = 1$$.
98+
So, this time, let's remove ourselves from any physics and instead solve the following ODE: $$y(t)' = -3y$$ with the initial condition that $$y(0) = 1$$.
9999
Note that in this case, the velocity is directly given by the ODE and the acceleration is not part of the model.
100100

101101
{% method %}
@@ -126,6 +126,8 @@ Full code for the visualization follows:
126126
[import, lang:"fortran"](code/fortran/euler.f90)
127127
{% sample lang="go" %}
128128
[import, lang:"go"](code/golang/euler.go)
129+
{% sample lang="js" %}
130+
[import, lang:"javascript"](code/javascript/euler.js)
129131
{% endmethod %}
130132

131133
<script>

0 commit comments

Comments
 (0)