看到一个求平方根的算法,用Swift实现了一下。
Talk is cheap. Show me the code.
func fixedPoint(fx: (Double)->Double, first: Double) -> Double {
let tolerance = 0.00001
func closeEnough(x: Double, y: Double) -> Bool {
return fabs(x - y) < tolerance
}
func Try(guess: Double) -> Double {
let next = fx(guess)
print("\(next), \(guess)")
if closeEnough(guess, y: next) {
return next
} else {
return Try(next)
}
}
return Try(first)
}
func Sqrt(x: Double) -> Double {
func calc(y: Double) -> Double {
func innerCalc(a: Double, b: Double) -> Double {
return (a+b)/2
}
return innerCalc(y, b: x/y)
}
return fixedPoint(calc, first: 1.0)
}
print(Sqrt(100))