Skip to content

Forward Euler in JavaScript #418

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
Oct 27, 2018
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions contents/forward_euler_method/code/javascript/euler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function forwardEuler(timeStep, n) {
const arr = [1];
for (let i = 1; i <= n; i++) {
arr[i] = arr[i - 1] - 3 * arr[i - 1] * timeStep;
}
return arr;
}

function checkEuler(arr, timeStep, threshold) {
const isApprox = true;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You made this a const, but you try to assign a new value further down. This function will either return true or crash. This is one of those cases where let is required.

arr.forEach((_value, i) => {
const solution = Math.exp(-3 * timeStep * i);

if (Math.abs(arr[i] - solution) > threshold) {
console.log(arr[i], solution);
isApprox = false;
}
});
return isApprox;
}

function main() {
const timeStep = 0.01;
const threshold = 0.01;
const n = 100;
let eulerResult = forwardEuler(timeStep, n);
let checkResult = checkEuler(eulerResult, timeStep, threshold);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eulerResult and checkResult can also be const.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok. GH did not notice me about the new review. I'm on it tomorrow.

console.log(checkResult);
}

main();
2 changes: 2 additions & 0 deletions contents/forward_euler_method/forward_euler_method.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ Full code for the visualization follows:
[import, lang:"matlab"](code/matlab/euler.m)
{% sample lang="swift" %}
[import, lang:"swift"](code/swift/euler.swift)
{% sample lang="js" %}
[import, lang:"javascript"](code/javascript/euler.js)
{% endmethod %}

<script>
Expand Down