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



我正在寻求计算ios中任何给定数字的平方根的方法,Objective C .我已经插入了使用日志执行此操作的方法。逻辑是。例如:求 5 的平方根

X = √5

然后

log10X = log10(√5)

这意味着

log10X = log10(5)/2;

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

所以我的答案在目标 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);

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

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

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

它可以从(Objective-(C使用:

#include "math.h"
double sqrtFive = sqrt(5.0);

和来自斯威夫特:

import Darwin // or Foundation, Cocoa, UIKit, ...
let sqrtFive = sqrt(5.0)

在 Swift 3 中,

 x = 4.0
 y = x.squareRoot()

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

最新更新