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
Changes from 1 commit
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
24 changes: 12 additions & 12 deletions contents/forward_euler_method/code/javascript/euler.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
function forwardEuler(time_step, n) {
function forwardEuler(timeStep, n) {
const arr = [1];
for (let i = 1; i <= n; i++) {
arr[i] = arr[i - 1] - 3 * arr[i - 1] * time_step;
arr[i] = arr[i - 1] - 3 * arr[i - 1] * timeStep;
}
return arr;
}

function checkEuler(arr, time_step, threshold) {
const is_approx = true;
arr.forEach(function callback(value, i) {
const solution = Math.exp(-3 * time_step * i);
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);
is_approx = false;
isApprox = false;
}
});
return is_approx;
return isApprox;
}

function main() {
const time_step = 0.01;
const timeStep = 0.01;
const threshold = 0.01;
const n = 100;
var euler_result = forwardEuler(time_step, n);
var check_result = checkEuler(euler_result, time_step, threshold);
console.log(check_result);
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();