在Swift中找到平方根的最简单方法? [英] Easiest way to find Square Root in Swift?

查看:525
本文介绍了在Swift中找到平方根的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图弄清楚如何在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.

任何输入或建议,将不胜感激.

Any input or suggestions would be greatly appreciated.

预先感谢

推荐答案

在Swift 3中,FloatingPoint协议似乎具有squareRoot()方法. FloatDouble都符合FloatingPoint协议.所以:

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()

就这么简单.

底层生成的代码应该是一条x86机器指令,不要跳转到函数的地址然后返回,因为这会转换为中间代码中内置的LLVM.因此,这应该比调用C库的sqrt函数更快[em] ,该函数实际上是一个函数,而不仅仅是汇编代码的宏.

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.

在Swift 3中,您不需要需要导入任何东西来使这项工作生效.

In Swift 3, you do not need to import anything to make this work.

这篇关于在Swift中找到平方根的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆