Skip to content

Commit 0500fce

Browse files
Wesley-ArringtonButt4cak3
authored andcommitted
Adding Forward Euler in Swift (#255)
1 parent 87ca7cb commit 0500fce

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import Foundation
2+
3+
func solveEuler(timeStep: Double, n: Int) -> [Double] {
4+
var result : [Double] = [1]
5+
6+
for i in 1...n {
7+
result.append(result[i - 1] - 3 * result[i - 1] * timeStep)
8+
}
9+
return result
10+
}
11+
12+
func checkResult(result: [Double], threshold: Double, timeStep: Double) -> Bool {
13+
var isApprox = true
14+
15+
for i in 0..<result.count {
16+
let solution = exp(-3 * Double(i) * timeStep)
17+
if abs(result[i] - solution) > threshold {
18+
print(result[i], solution)
19+
isApprox = false
20+
}
21+
}
22+
return isApprox
23+
}
24+
25+
func main() {
26+
let timeStep = 0.01
27+
let n = 100
28+
let threshold = 0.01
29+
30+
let result = solveEuler(timeStep: timeStep, n: n)
31+
let isApprox = checkResult(result: result, threshold: threshold, timeStep: timeStep)
32+
33+
if isApprox {
34+
print("All values within threshold")
35+
} else {
36+
print("Value(s) not in threshold")
37+
}
38+
}
39+
40+
main()

contents/forward_euler_method/forward_euler_method.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,8 @@ Full code for the visualization follows:
119119
[import, lang:"haskell"](code/haskell/euler.hs)
120120
{% sample lang="m" %}
121121
[import, lang:"matlab"](code/matlab/euler.m)
122+
{% sample lang="swift" %}
123+
[import, lang:"swift"](code/swift/euler.swift)
122124
{% endmethod %}
123125

124126
<script>

0 commit comments

Comments
 (0)