Easiest way to find Square Root in Swift?

前端 未结 6 1853
小鲜肉
小鲜肉 2021-02-18 22:00

I have been trying to figure out how to programmatically find a square root of a number in Swift. I am looking for the simplest possible way to accomplish with as little code ne

6条回答
  •  盖世英雄少女心
    2021-02-18 22:22

    this should work for any root, 2 - , but you probably don't care:

    func root(input: Double, base: Int = 2) -> Double {
        var output = 0.0
        var add = 0.0
        while add < 16.0 {
            while pow(output, base) <= input {
                output += pow(10.0, (-1.0 * add))
            }
            output -= pow(10.0, (-1.0 * add))
            add += 1.0
        }
        return output + 0.0
    }
    

提交回复
热议问题