24

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Bigfoot11
  • 911
  • 2
  • 11
  • 25
  • 8
    possible duplicate of [Mathematical functions in Swift](http://stackoverflow.com/questions/24012511/mathematical-functions-in-swift) – Evorlor Jun 30 '15 at 19:12

6 Answers6

46

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.

Tim Vermeulen
  • 12,352
  • 9
  • 44
  • 63
Paul Buis
  • 805
  • 7
  • 7
10

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
Laughing Vergil
  • 3,706
  • 1
  • 14
  • 28
6

First import import UIKit

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

Then your result should be on the "result" variable

Eddy Ekofo
  • 541
  • 6
  • 13
  • 1
    While this code may answer the question, providing additional context regarding **how** and/or **why** it solves the problem would improve the answer's long-term value. – Alexander Apr 01 '18 at 06:41
3

sqrt function for example sqrt(4.0)

Nikita Leonov
  • 5,684
  • 31
  • 37
1

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
}
Community
  • 1
  • 1
  • 3
    It is highly recommended to not implement functions that are already available in iOS SDK, Check : https://developer.apple.com/documentation/swift/double/2885715-squareroot – Amir.n3t Oct 13 '19 at 03:39
0
func sqrt(num:Int)-> Double {
    var x1:Double = (Double(num) * 1.0) / 2; 
    var x2:Double = (x1 + (Double(num) / x1)) / 2; 
    while(abs(x1 - x2) >= 0.0000001){
        x1 = x2; 
        x2 = (x1 + (Double(num) / x1)) / 2;
        }
    return Double(x2);
  }
print(sqrt(num:2))

**output**
1.414


  [1]: https://i.stack.imgur.com/SuLPj.png