Skip to content

Commit 03912e7

Browse files
depateButt4cak3
authored andcommitted
Forward Euler in JavaScript (#418)
1 parent 6d7013d commit 03912e7

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function forwardEuler(timeStep, n) {
2+
const arr = [1];
3+
for (let i = 1; i <= n; i++) {
4+
arr[i] = arr[i - 1] - 3 * arr[i - 1] * timeStep;
5+
}
6+
return arr;
7+
}
8+
9+
function checkEuler(arr, timeStep, threshold) {
10+
let isApprox = true;
11+
arr.forEach((_value, i) => {
12+
const solution = Math.exp(-3 * timeStep * i);
13+
14+
if (Math.abs(arr[i] - solution) > threshold) {
15+
console.log(arr[i], solution);
16+
isApprox = false;
17+
}
18+
});
19+
return isApprox;
20+
}
21+
22+
function main() {
23+
const timeStep = 0.01;
24+
const threshold = 0.01;
25+
const n = 100;
26+
const eulerResult = forwardEuler(timeStep, n);
27+
const checkResult = checkEuler(eulerResult, timeStep, threshold);
28+
console.log(checkResult);
29+
}
30+
31+
main();

contents/forward_euler_method/forward_euler_method.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,8 @@ Full code for the visualization follows:
122122
[import, lang:"matlab"](code/matlab/euler.m)
123123
{% sample lang="swift" %}
124124
[import, lang:"swift"](code/swift/euler.swift)
125+
{% sample lang="js" %}
126+
[import, lang:"javascript"](code/javascript/euler.js)
125127
{% sample lang="f90" %}
126128
[import, lang:"fortran"](code/fortran/euler.f90)
127129
{% sample lang="go" %}

0 commit comments

Comments
 (0)