Created
June 21, 2014 18:06
-
-
Save mikeash/3d2f115fc3542104f0f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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