Skip to content

Adding Forward Euler in Swift #255

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 1 commit into from
Jul 21, 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
40 changes: 40 additions & 0 deletions contents/forward_euler_method/code/swift/euler.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
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()
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 @@ -119,6 +119,8 @@ Full code for the visualization follows:
[import, lang:"haskell"](code/haskell/euler.hs)
{% sample lang="m" %}
[import, lang:"matlab"](code/matlab/euler.m)
{% sample lang="swift" %}
[import, lang:"swift"](code/swift/euler.swift)
{% endmethod %}

<script>
Expand Down