计算 ios 、 Objective C 和 Swift 中任何数字的平方根的最佳方法

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

我正在询问如何计算 iosObjective C 中任何给定数字的平方根。我已经使用日志插入了我的方式。逻辑是。例如:求 5

的平方根
X = √5

然后

log10X = log10(√5)

这意味着

log10X = log10(5)/2;

然后应该从 2 获取 log10(5)divide 的值,然后应该获取该值的 antilog 以搜索 X .

所以我的答案是 Objective C 如下所示(例如:我正在搜索 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);

如果有人有其他的way/answers。要获得任何给定值的平方根,请添加并接受上述答案的建议。

这也对 swift 开发人员开放。请也添加答案,因为这将有助于任何想要计算任何给定数字的平方根的人。

sqrt 函数(以及其他数学函数)是 在所有 OS X 和 iOS 平台上的标准库中可用。

可以从(Objective-)C:

使用
#include "math.h"

double sqrtFive = sqrt(5.0);

来自Swift:

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

let sqrtFive = sqrt(5.0)

在Swift3、

 x = 4.0
 y = x.squareRoot()

因为 FloatingPoint 协议有一个 squareRoot 方法并且 FloatDouble 都符合 FloatingPoint 协议。这应该比来自 Darwin 或 Glibc 的 sqrt() 函数具有更高的性能,因为它生成的代码将来自 LLVM 内置平方根,因此在具有硬件平方根机器代码的系统上没有函数调用开销。