The easiest way to find the square root in Swift?

I was trying to figure out how to programmatically find the square root of a number in Swift. I am looking for the simplest possible way to execute with a little code. I'm probably pretty easy to do now, but can't figure out how to do this.

Any materials or suggestions are welcome.

Thanks in advance

+17
math swift square-root
source share
5 answers

In Swift 3, the FloatingPoint protocol has a squareRoot() method. Both Float and Double compliant with the FloatingPoint protocol. So:

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

about as simple as him.

The generated code should be based on one x86 machine instruction, without going to the function address, and then return, because this translates to LLVM, which is built into the intermediate code. Thus, it should be faster than calling the C sqrt library function, which is really a function, not just a macro for assembly code.

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

+37
source share

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

  • Uikit
  • Cocoa
    • You can simply import Darwin instead of the full Cocoa
  • Fund
+9
source share

First import import UIKit

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

Then your result should be in the variable "result"

+4
source share

Sqrt function e.g. sqrt(4.0)

+2
source share

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 } 
0
source share

All Articles