Easiest way to find Square Root in Swift?

百般思念 提交于 2020-01-01 07:37:19

问题


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 needed. I now this is probably fairly easy to accomplish, but can't figure out a way to do it.

Any input or suggestions would be greatly appreciated.

Thanks in advance


回答1:


In Swift 3, the FloatingPoint protocol appears to have a squareRoot() method. Both Float and Double conform to the FloatingPoint protocol. So:

let x = 4.0
let y = x.squareRoot()

is about as simple as it gets.

The underlying generated code should be a single x86 machine instruction, no jumping to the address of a function and then returning because this translates to an LLVM built-in in the intermediate code. So, this should be faster than invoking the C library's sqrt function, which really is a function and not just a macro for assembly code.

In Swift 3, you do not need to import anything to make this work.




回答2:


Note that sqrt() will require the import of at least one of:

  • UIKit
  • Cocoa
    • You can just import Darwin instead of the full Cocoa
  • Foundation



回答3:


First import import UIKit

let result = sqrt(25) // equals to 5

Then your result should be on the "result" variable




回答4:


sqrt function for example sqrt(4.0)




回答5:


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
}


来源:https://stackoverflow.com/questions/31146467/easiest-way-to-find-square-root-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!