4

I am asking for ways to calculate the square root of any given number in ios, Objective C. I have inserted my way to do it using log. the logic was. ex : find the square root of 5

X = √5

then

log10X = log10(√5)

this means

log10X = log10(5)/2;

then should get the value of log10(5) and divide it from 2 and after that shoud get the antilog of that value to search X.

so my answer is in Objective C is like below (as an ex: I'm searching the square root of 5)

double getlogvalue = log10(5)/2; // in here the get the value of 5 in log10 and divide it from two.

//then get the antilog value for the getlogvalue

double getangilogvalue = pow(10,getlogvalue);

//this will give the square root of any number. and the answer may include for few decimal points. so to print with two decimal point,

NSLog(@"square root of the given number  is : %.02f", getantilogvalue);

If anyone have any other way/answers. to get the square root of any given value , add please add and also suggestions for above answer is also accepted.

This is open for swift developers too. please add there answers also, becasue this will help to anyone who want to calculate the square root of any given number.

caldera.sac
  • 4,918
  • 7
  • 37
  • 69

2 Answers2

11

The sqrt function (and other mathematical functions as well) is available in the standard libraries on all OS X and iOS platforms.

It can be used from (Objective-)C:

#include "math.h"

double sqrtFive = sqrt(5.0);

and from Swift:

import Darwin // or Foundation, Cocoa, UIKit, ...

let sqrtFive = sqrt(5.0)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • just to know , do we have to `import` `"math.h"`, or can't we use it defaultly without import . – caldera.sac Aug 28 '16 at 10:22
  • @AnuradhS: You have to include "math.h" (or any other header which includes "math.h"). Otherwise the function is assumed to return an `int` – and Xcode should warn you about "implicitly declaring a function". – Martin R Aug 28 '16 at 10:26
  • In pure Swift 3+: `import Swift; let sqrtFive = 5.0.squareRoot()` – Cœur Oct 10 '18 at 08:58
  • @Cœur: Yes, that is what Paul said (it was not available at the time when I wrote this answer). – Martin R Oct 10 '18 at 09:04
2

In Swift 3,

 x = 4.0
 y = x.squareRoot()

since the FloatingPoint protocol has a squareRoot method and both Float and Double comply with the FloatingPoint protocol. This should be higher performance than the sqrt() function from either Darwin or Glibc, since the code it generates will be from the LLVM built-in square root, so no function call overhead on systems with hardware square root machine code.

Paul Buis
  • 805
  • 7
  • 7
  • 1
    As far as I can see, the generated assembly code is the same for `sqrt(x)` and `x.squareRoot()`, at least on the macosx platform. – Martin R Dec 12 '16 at 17:19