ios - 让 Swift 假设三角函数计算的度数

标签 ios swift trigonometry

是否可以更改 Swift for iOS 中的设置、属性等,以便它采用度数而不是弧度进行三角计算?

例如 sin(90) 将计算为 1

我有:

let pi = 3.14 
var r2d = 180.0/pi
var d2r = pi/180

...但是对于一些较长的三角方程,转换确实涉及到。

最佳答案

正如在其他答案中已经说过的,标准库中没有以度为单位的参数的三角函数。

如果您定义自己的函数,那么您可以使用__sinpi()__cospi() 等...而不是乘以 π:

// Swift 2:
func sin(degrees degrees: Double) -> Double {
    return __sinpi(degrees/180.0)
}

// Swift 3:
func sin(degrees: Double) -> Double {
    return __sinpi(degrees/180.0)
}

来自__sinpi manual page (强调):

The __sinpi() function returns the sine of pi times x (measured in radians). This can be computed more accurately than sin(M_PI * x), because it can implicitly use as many bits of pi as are necessary to deliver a well-rounded result, instead of the 53-bits to which M_PI is limited. For large x it may also be more efficient, as the argument reduction involved is significantly simpler.

__sinpi() 和相关函数是非标准的,但是 适用于 iOS 7/OS X 10.9 及更高版本。

示例:

sin(degrees: 180.0)       // 0

给出一个准确的结果,对比于:

sin(180.0 * M_PI/180.0) // 1.224646799147353e-16

只是为了好玩:这就是你如何为所有浮点类型定义基于度数的正弦函数,包括 CGFloat 函数重载(现在针对 Swift 3 更新):

func sin(degrees: Double) -> Double {
    return __sinpi(degrees/180.0)
}

func sin(degrees: Float) -> Float {
    return __sinpif(degrees/180.0)
}

func sin(degrees: CGFloat) -> CGFloat {
    return CGFloat(sin(degrees: degrees.native))
}

在最后一个变体中,编译器自动从 要调用的函数的 degrees.native 的实际类型,因此 在 32 位和 64 位平台上都能正常工作。

关于ios - 让 Swift 假设三角函数计算的度数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28598307/

相关文章:

ios - 我正在尝试 Segue 并传递一个字符串,但出现错误

swift - 如何使用 Swift 在 xCode 中将 textField 的字符串转换为 Double

r - 如何将正弦变换后的向量转换回原始向量?

ios - 按下 “Edit” UITableViewRowAction 时无法切换到另一个 UIViewController

ios - 如何在iOS中实现“拆分”功能

iphone - 获得适当时间的问题

ios - MFMailComposer toReceiptsText 延迟

java - 将速度X和速度Y转换为角度

javascript - Trig/javascript 计算在不裁剪的情况下适应图像旋转所需的填充

ios - 带有 sqlite 的核心数据仅返回 3 行