Files
cell/docs/library/math.md

159 lines
2.3 KiB
Markdown

---
title: "math"
description: "Trigonometry, logarithms, and roots"
weight: 70
type: "docs"
---
ƿit provides three math modules with identical functions but different angle representations:
```javascript
var math = use('math/radians') // angles in radians
var math = use('math/degrees') // angles in degrees
var math = use('math/cycles') // angles in cycles (0-1)
```
## Trigonometry
### sine(angle)
```javascript
math.sine(math.pi / 2) // 1 (radians)
math.sine(90) // 1 (degrees)
math.sine(0.25) // 1 (cycles)
```
### cosine(angle)
```javascript
math.cosine(0) // 1
```
### tangent(angle)
```javascript
math.tangent(math.pi / 4) // 1 (radians)
```
### arc_sine(n)
Inverse sine.
```javascript
math.arc_sine(1) // pi/2 (radians)
```
### arc_cosine(n)
Inverse cosine.
```javascript
math.arc_cosine(0) // pi/2 (radians)
```
### arc_tangent(n, denominator)
Inverse tangent. With two arguments, computes atan2.
```javascript
math.arc_tangent(1) // pi/4 (radians)
math.arc_tangent(1, 1) // pi/4 (radians)
math.arc_tangent(-1, -1) // -3pi/4 (radians)
```
## Exponentials and Logarithms
### e(power)
Euler's number raised to a power. Default power is 1.
```javascript
math.e() // 2.718281828...
math.e(2) // e^2
```
### ln(n)
Natural logarithm (base e).
```javascript
math.ln(math.e()) // 1
```
### log(n)
Base 10 logarithm.
```javascript
math.log(100) // 2
```
### log2(n)
Base 2 logarithm.
```javascript
math.log2(8) // 3
```
## Powers and Roots
### power(base, exponent)
```javascript
math.power(2, 10) // 1024
```
### sqrt(n)
Square root.
```javascript
math.sqrt(16) // 4
```
### root(radicand, n)
Nth root.
```javascript
math.root(27, 3) // 3 (cube root)
```
## Constants
Available in the radians module:
```javascript
math.pi // 3.14159...
math.e() // 2.71828...
```
## Example
```javascript
var math = use('math/radians')
// Distance between two points
var distance = function(x1, y1, x2, y2) {
var dx = x2 - x1
var dy = y2 - y1
return math.sqrt(dx * dx + dy * dy)
}
// Angle between two points
var angle = function(x1, y1, x2, y2) {
return math.arc_tangent(y2 - y1, x2 - x1)
}
// Rotate a point
var rotate = function(x, y, a) {
var c = math.cosine(a)
var s = math.sine(a)
return {
x: x * c - y * s,
y: x * s + y * c
}
}
```