Skip to content

Commit 70b508c

Browse files
Julianzsparal
Julian
authored andcommitted
add the forward euler method in golang (#485)
* add the forward euler method in golang * change the name golang to go
1 parent 51543db commit 70b508c

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math"
6+
)
7+
8+
func forwardEuler(timeStep float64, n int) []float64 {
9+
result := make([]float64, n)
10+
result[0] = 1
11+
for x := 1; x < n; x++ {
12+
result[x] = result[x-1] - 3*result[x-1]*timeStep
13+
}
14+
return result
15+
}
16+
17+
func check(result []float64, threshold, timeStep float64) bool {
18+
approx := true
19+
for x := 0.; int(x) < len(result); x++ {
20+
solution := math.Exp(-3. * x * timeStep)
21+
if math.Abs(result[int(x)]-solution) > threshold {
22+
fmt.Println(result[int(x)], solution)
23+
approx = false
24+
}
25+
}
26+
return approx
27+
}
28+
29+
func main() {
30+
timeStep, threshold := .01, .01
31+
n := 100
32+
33+
result := forwardEuler(timeStep, n)
34+
if check(result, threshold, timeStep) {
35+
fmt.Println("All values within threshold")
36+
} else {
37+
fmt.Println("Value(s) not within threshold")
38+
}
39+
}

contents/forward_euler_method/forward_euler_method.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,8 @@ Full code for the visualization follows:
123123
[import, lang:"swift"](code/swift/euler.swift)
124124
{% sample lang="f90" %}
125125
[import, lang:"fortran"](code/fortran/euler.f90)
126+
{% sample lang="go" %}
127+
[import, lang:"go"](code/golang/euler.go)
126128
{% endmethod %}
127129

128130
<script>

0 commit comments

Comments
 (0)