mrBallista - 11 months ago 140

Swift Question

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 ?

Answer

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