为三角计算制作Swift假设学位 [英] Make Swift Assume Degrees for Trigonometry Calculations

查看:99
本文介绍了为三角计算制作Swift假设学位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Swift for iOS中更改设置,属性等,以便它假定三角计算的度数而不是弧度?

Is it possible to change a setting, property, etc in Swift for iOS so that it assumes degrees for trigonometry calculations rather than radians?

例如 sin(90)将被评估为 1

我有:

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

...但转换实际上涉及一些长三角方程式。

... but the conversions are getting really involved for some of the long trig equations.

推荐答案

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

As already said in the other answers, there are no trigonometric functions in the standard library that take the arguments in degrees.

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

If you define your own function then you can use __sinpi(), __cospi(), etc ... instead of multiplying by π:

// 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)
}

来自< a href =https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/__sinpi.3.html\"rel =noreferrer> __ sinpi 手册页(强调添加):

From the __sinpi manual page (emphasis added):



__sinpi()
函数返回pi乘以x的正弦值(以
弧度计)。这可以比sin(M_PI * x)更准确计算,因为它可以隐含地使用
所需的pi位数来提供全面的结果,而不是53 M_PI受限的-bits。对于大的x,它可能 b 更有效,因为参数减少要简单得多。

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及更高版本上的
可用。

__sinpi() and the related functions are non-standard, but available on iOS 7/OS X 10.9 and later.

示例:

sin(degrees: 180.0)       // 0

给出一个确切的结果,与之相反:

gives an exact result, in contrast to:

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






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


And just for fun: This is how you can define the degree-based sine function for all floating point types, including CGFloat with function overloading (now updated for 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位平台上。

In the last variant, the compiler automatically infers from the actual type of degrees.native which function to call, so that this works correctly on both 32-bit and 64-bit platforms.

这篇关于为三角计算制作Swift假设学位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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