Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 312
mrBallista Avatar asked Mar 07 '26 15:03

mrBallista


2 Answers

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.

like image 150
Martin R Avatar answered Mar 10 '26 07:03

Martin R


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.

like image 24
mark_dimitry Avatar answered Mar 10 '26 07:03

mark_dimitry