Skip to content

Instantly share code, notes, and snippets.

@mikeash
Created June 21, 2014 18:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeash/3d2f115fc3542104f0f1 to your computer and use it in GitHub Desktop.
Save mikeash/3d2f115fc3542104f0f1 to your computer and use it in GitHub Desktop.
protocol Arithmeticable {
init(_ v: Int)
func +(lhs: Self, rhs: Self) -> Self
func -(lhs: Self, rhs: Self) -> Self
func *(lhs: Self, rhs: Self) -> Self
func /(lhs: Self, rhs: Self) -> Self
}
extension Int: Arithmeticable {}
extension Double: Arithmeticable {}
func sqrt<T: Arithmeticable>(x: T) -> T {
var guess = x;
for i in 0..100 {
guess = (guess + x / guess) / T(2)
}
return guess
}
func quadratic<T: Arithmeticable>(a: T, b: T, c: T) -> (T, T) {
return (
(T(0)-b + sqrt(b * b - T(4) * a * c)) / (T(2) * a),
(T(0)-b - sqrt(b * b - T(4) * a * c)) / (T(2) * a)
)
}
println(quadratic(1, 0, -1))
println(quadratic(2.0, 0.0, -1.0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment