Skip to content

Add Java implementation of Forward Euler #518

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 4 commits into from
Oct 27, 2018
Merged
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
38 changes: 38 additions & 0 deletions contents/forward_euler_method/code/java/ForwardEuler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
public class ForwardEuler {
private static double[] solveEuler(double timestep, int n) {
double[] eulerResult = new double[n];

//Setting the initial condition
eulerResult[0] = 1;
for(int i = 1; i < eulerResult.length; i++) {
eulerResult[i] = eulerResult[i - 1] - (3 * eulerResult[i - 1] * timestep);
}
return eulerResult;
}

private static boolean checkResult(double[] eulerResult, double threshold, double timestep) {
boolean isApprox = true;

for(int i = 0; i < eulerResult.length; i++) {
double time = i * timestep;
double solution = Math.exp(-3 * time);
if(Math.abs(eulerResult[i] - solution) > threshold) {
System.out.println(eulerResult[i] + " " + solution);
isApprox = false;
}
}

return isApprox;
}

public static void main(String[] args) {
double timestep = 0.1;
int n = 100;
double threshold = 0.1;

double[] eulerResult = solveEuler(timestep, n);
boolean isApprox = checkResult(eulerResult, threshold, timestep);

System.out.println(isApprox);
}
}
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 @@ -128,6 +128,8 @@ Full code for the visualization follows:
[import, lang:"go"](code/golang/euler.go)
{% sample lang="asm-x64" %}
[import, lang:"asm-x64"](code/asm-x64/euler.s)
{% sample lang="java" %}
[import, lang:"java"](code/java/ForwardEuler.java)
{% endmethod %}

<script>
Expand Down