Skip to content

Commit 1bb82d9

Browse files
atocilButt4cak3
authored andcommitted
Add Java implementation of Forward Euler (#518)
1 parent 329409c commit 1bb82d9

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
public class ForwardEuler {
2+
private static double[] solveEuler(double timestep, int n) {
3+
double[] eulerResult = new double[n];
4+
5+
//Setting the initial condition
6+
eulerResult[0] = 1;
7+
for(int i = 1; i < eulerResult.length; i++) {
8+
eulerResult[i] = eulerResult[i - 1] - (3 * eulerResult[i - 1] * timestep);
9+
}
10+
return eulerResult;
11+
}
12+
13+
private static boolean checkResult(double[] eulerResult, double threshold, double timestep) {
14+
boolean isApprox = true;
15+
16+
for(int i = 0; i < eulerResult.length; i++) {
17+
double time = i * timestep;
18+
double solution = Math.exp(-3 * time);
19+
if(Math.abs(eulerResult[i] - solution) > threshold) {
20+
System.out.println(eulerResult[i] + " " + solution);
21+
isApprox = false;
22+
}
23+
}
24+
25+
return isApprox;
26+
}
27+
28+
public static void main(String[] args) {
29+
double timestep = 0.1;
30+
int n = 100;
31+
double threshold = 0.1;
32+
33+
double[] eulerResult = solveEuler(timestep, n);
34+
boolean isApprox = checkResult(eulerResult, threshold, timestep);
35+
36+
System.out.println(isApprox);
37+
}
38+
}

contents/forward_euler_method/forward_euler_method.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@ Full code for the visualization follows:
130130
[import, lang:"go"](code/golang/euler.go)
131131
{% sample lang="asm-x64" %}
132132
[import, lang:"asm-x64"](code/asm-x64/euler.s)
133+
{% sample lang="java" %}
134+
[import, lang:"java"](code/java/ForwardEuler.java)
133135
{% endmethod %}
134136

135137
<script>

0 commit comments

Comments
 (0)