Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to find Square Root in Swift?

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.

like image 946
Bigfoot11 Avatar asked Jun 30 '15 19:06

Bigfoot11


People also ask

What is the fastest way to find the square root?

The steps to estimate the square root of a 5 digit number are: Step 1: First pair the digits starting from right to left. Step 2: Match the unit digit of number from the chart and determine the possible values of the square root of the unit digit. Step 3: Let us consider the group of the first three digits.


4 Answers

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.

like image 85
Paul Buis Avatar answered Oct 11 '22 09:10

Paul Buis


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
like image 36
Laughing Vergil Avatar answered Oct 11 '22 10:10

Laughing Vergil


First import import UIKit

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

Then your result should be on the "result" variable

like image 32
Eddy Ekofo Avatar answered Oct 11 '22 11:10

Eddy Ekofo


sqrt function for example sqrt(4.0)

like image 20
Nikita Leonov Avatar answered Oct 11 '22 09:10

Nikita Leonov