Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to calculate the square root of any number in ios , Objective C and Swift

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.

like image 348
Chanaka Anuradh Caldera Avatar asked Dec 10 '22 15:12

Chanaka Anuradh Caldera


1 Answers

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)
like image 164
Martin R Avatar answered May 13 '23 15:05

Martin R