简体   繁体   中英

Arcus Cotangent implementation in Swift

How can arcus cotangent (arccot) be implemented in swift? Which library is necessary to import, i am using Darwin but i cant see it when trying to call ?

All mathematical functions from <math.h> are available in Swift if you

import Darwin

(which is automatically imported if you import Foundation or UIKit).

Now the inverse cotangent function is not among these, but you can easily compute it from atan() using the relationships (see for example Inverse trigonometric functions ):

arccot(x) = arctan(1/x)        (for x > 0)
arccot(x) = π + arctan(1/x)    (for x < 0)

arccot(x) = π/2 - atan(x)

The first two formulae are numerically better suited for large (absolute) values of x , and the last one is better for small values, so you could define your acot() function as

func acot(x : Double) -> Double {
    if x > 1.0 {
        return atan(1.0/x)
    } else if x < -1.0 {
        return M_PI + atan(1.0/x)
    } else {
        return M_PI_2 - atan(x)
    }
}

For Swift 3 replace M_PI by Double.pi .

In Swift 4 (iOS 11, Xcode 9)

After placing import UIKit , you can write something like:

let fi = atan(y/x)

Where x and y of type CGFloat (in my case).

Or you can use others if needed:

let abc = acos(y)

Math functions work with argument types: Double, Float, CGFloat etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM