Skip to content

Euler method in js #511

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
35 changes: 35 additions & 0 deletions contents/forward_euler_method/code/javascript/euler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
function solveEuler(timeStep, n){
const result = [];
if (n != 0) {
result[0] = 1;
for (let i = 1; i < n; ++i) {
result[i] = result[i-1] - 3 * result[i-1] * timeStep;
Copy link
Member

@PudottaPommin PudottaPommin Oct 21, 2018

Choose a reason for hiding this comment

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

result[i-1] should use spaces around - so it looks like result[i - 1]

}
}
return result;
}

function checkResult(result, threshold, timeStep) {
let approx = true;
for (let i = 0; i < result.length; ++i) {
const solution = Math.exp(-3 * i * timeStep);
if (Math.abs(result[i] - solution) > threshold) {
console.log(result[i] + " " + solution);
approx = false;
}
}
return approx;
}

const timeStep = 0.01;
const n = 100;
const threshold = 0.01;

const result = solveEuler(timeStep, n)
const approx = checkResult(result, threshold, timeStep)

if (approx) {
console.log("All values within threshold");
} else {
console.log("Value(s) not in threshold");
}
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 @@ -126,6 +126,8 @@ Full code for the visualization follows:
[import, lang:"fortran"](code/fortran/euler.f90)
{% sample lang="go" %}
[import, lang:"go"](code/golang/euler.go)
{% sample lang="js" %}
[import, lang:"javascript"](code/javascript/euler.js)
{% endmethod %}

<script>
Expand Down