forked from algorithm-archivists/algorithm-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
euler.swift
42 lines (32 loc) · 948 Bytes
/
euler.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import Foundation
func solveEuler(timeStep: Double, n: Int) -> [Double] {
var result : [Double] = [1]
for i in 1...n {
result.append(result[i - 1] - 3 * result[i - 1] * timeStep)
}
return result
}
func checkResult(result: [Double], threshold: Double, timeStep: Double) -> Bool {
var isApprox = true
for i in 0..<result.count {
let solution = exp(-3 * Double(i) * timeStep)
if abs(result[i] - solution) > threshold {
print(result[i], solution)
isApprox = false
}
}
return isApprox
}
func main() {
let timeStep = 0.01
let n = 100
let threshold = 0.01
let result = solveEuler(timeStep: timeStep, n: n)
let isApprox = checkResult(result: result, threshold: threshold, timeStep: timeStep)
if isApprox {
print("All values within threshold")
} else {
print("Value(s) not in threshold")
}
}
main()