Intial Commit

This commit is contained in:
valki
2020-10-17 18:42:50 +02:00
commit 664c6d8ca3
5892 changed files with 759183 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
# Chaining
This page has been moved [here](core/chaining.md).

View File

@@ -0,0 +1,87 @@
# Command Line Interface (CLI)
When math.js is installed globally using npm, its expression parser can be used
from the command line. To install math.js globally:
```bash
$ npm install -g mathjs
```
Normally, a global installation must be run with admin rights (precede the
command with `sudo`). After installation, the application `mathjs` is available
via the command line:
```bash
$ mathjs
> 12 / (2.3 + 0.7)
4
> 5.08 cm to inch
2 inch
> sin(45 deg) ^ 2
0.5
> 9 / 3 + 2i
3 + 2i
> det([-1, 2; 3, 1])
-7
```
The command line interface can be used to open a prompt, to execute a script,
or to pipe input and output streams:
```bash
$ mathjs # Open a command prompt
$ mathjs script.txt # Run a script file, output to console
$ mathjs script1.txt script2.txt # Run two script files
$ mathjs script.txt > results.txt # Run a script file, output to file
$ cat script.txt | mathjs # Run input stream, output to console
$ cat script.txt | mathjs > results.txt # Run input stream, output to file
```
You can also use it to create LaTeX from or sanitize your expressions using the
`--tex` and `--string` options:
```bash
$ mathjs --tex
> 1/2
\frac{1}{2}
```
```bash
$ mathjs --string
> (1+1+1)
(1 + 1 + 1)
```
To change the parenthesis option use the `--parenthesis=` flag:
```bash
$ mathjs --string --parenthesis=auto
> (1+1+1)
1 + 1 + 1
```
```bash
$ mathjs --string --parenthesis=all
> (1+1+1)
(1 + 1) + 1
```
# Command line debugging (REPL)
For debugging purposes, `bin/repl.js` provides a REPL (Read Evaluate Print Loop)
for interactive testing of mathjs without having to build new build files after every
little change to the source files. You can either start it directly (`./bin/repl.js`) or
via node (`node bin/repl.js`).
You can exit using either [ctrl]-[C] or [ctrl]-[D].
```bash
$ ./bin/repl.js
> math.parse('1+1')
{ op: '+',
fn: 'add',
args:
[ { value: '1', valueType: 'number' },
{ value: '1', valueType: 'number' } ] }
>
```

View File

@@ -0,0 +1,3 @@
# Configuration
This page has been moved [here](core/configuration.md).

3
nodered/rootfs/data/node_modules/mathjs/docs/core.md generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# Core
This page has been moved [here](core/index.md).

View File

@@ -0,0 +1,41 @@
# Chaining
Math.js supports chaining operations by wrapping a value into a `Chain`.
A chain can be created with the function `math.chain(value)`
(formerly `math.select(value)`).
All functions available in the math namespace can be executed via the chain.
The functions will be executed with the chain's value as the first argument,
followed by extra arguments provided by the function call itself.
```js
math.chain(3)
.add(4)
.subtract(2)
.done(); // 5
math.chain( [[1, 2], [3, 4]] )
.subset(math.index(0, 0), 8)
.multiply(3)
.done(); // [[24, 6], [9, 12]]
```
### API
A `Chain` is constructed as:
```js
math.chain()
math.chain(value)
```
The `Chain` has all functions available in the `math` namespace, and has
a number of special functions:
- `done()`
Finalize the chain and return the chain's value.
- `valueOf()`
The same as `done()`, returns the chain's value.
- `toString()`
Executes `math.format(value)` onto the chain's value, returning
a string representation of the value.

View File

@@ -0,0 +1,125 @@
# Configuration
Math.js contains a number of configuration options. There are two ways to
configure math.js:
- Configure an existing instance of math.js using `math.config(options)`,
for example `math.config({number: 'BigNumber'})` to change to BigNumbers.
- Create and configure a new instance of math.js using `math.create([options])`,
for example `var bigmath = math.create({number: 'BigNumber'})` to create a new
instance configured to use BigNumbers.
The following configuration options are available:
- `epsilon`. The minimum relative difference used to test equality between two
compared values. This value is used by all relational functions.
Default value is `1e-14`.
- `matrix`. The default type of matrix output for functions.
Available values are: `'Matrix'` (default) or `'Array'`.
Where possible, the type of matrix output from functions is determined from
the function input: An array as input will return an Array, a Matrix as input
will return a Matrix. In case of no matrix as input, the type of output is
determined by the option `matrix`. In case of mixed matrix
inputs, a matrix will be returned always.
- `number`. The default type of numbers. This setting is used by functions
like `eval` which cannot determine the correct type of output from the
functions input. For most functions though, the type of output is determined
from the the input: a number as input will return a number as output,
a BigNumber as input returns a BigNumber as output.
Available values are: `'number'` (default), `'BigNumber'`, or `'Fraction'`.
[BigNumbers](../datatypes/bignumbers.js) have higher precision than the default
numbers of JavaScript, and [`Fractions`](../datatypes/fractions.js) store
values in terms of a numerator and denominator.
- `precision`. The maximum number of significant digits for bigNumbers.
This setting only applies to BigNumbers, not to numbers.
Default value is `64`.
- `predictable`. Predictable output type of functions. When true, output type
depends only on the input types. When false (default), output type can vary
depending on input values. For example `math.sqrt(-4)` returns `complex('2i')` when
predictable is false, and returns `NaN` when true.
Predictable output can be needed when programmatically handling the result of
a calculation, but can be inconvenient for users when evaluating dynamic
equations.
## Examples
This section shows a number of configuration examples.
### node.js
```js
// load the default instance of math.js
var math = require('mathjs');
// range will output a Matrix
math.range(0, 4); // Matrix [0, 1, 2, 3]
// create a new instance configured to use Arrays
var math2 = math.create({
matrix: 'Array' // Choose 'Matrix' (default) or 'Array'
});
// range will output an Array
math2.range(0, 4); // Array [0, 1, 2, 3]
// change the configuration of math2 from Arrays to Matrices
math2.config({
matrix: 'Matrix' // Choose 'Matrix' (default) or 'Array'
});
// range will output a Matrix
math2.range(0, 4); // Matrix [0, 1, 2, 3]
// create an instance of math.js with BigNumber configuration
var bigmath = math.create({
number: 'BigNumber', // Choose 'number' (default), 'BigNumber', or 'Fraction'
precision: 32 // 64 by default, only applicable for BigNumbers
});
// parser will parse numbers as BigNumber now:
bigmath.eval('1 / 3'); // BigNumber, 0.33333333333333333333333333333333
```
### browser
```html
<!DOCTYPE HTML>
<html>
<head>
<script src="math.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
// the default instance of math.js is available as 'math'
// range will output a Matrix
math.range(0, 4); // Matrix [0, 1, 2, 3]
// change the configuration of math from Matrices to Arrays
math.config({
matrix: 'Array' // Choose 'Matrix' (default) or 'Array'
});
// range will output an Array
math.range(0, 4); // Array [0, 1, 2, 3]
// create a new instance of math.js with bignumber configuration
var bigmath = math.create({
number: 'BigNumber', // Choose 'number' (default), 'BigNumber', or 'Fraction'
precision: 32 // 64 by default, only applicable for BigNumbers
});
// parser will parse numbers as BigNumber now:
bigmath.eval('1 / 3'); // BigNumber, 0.33333333333333333333333333333333
</script>
</body>
</html>
```

View File

@@ -0,0 +1,236 @@
# Extension
The library can easily be extended with functions and variables using the
[`import`](../reference/functions/import.md) function. The function `import`
accepts an object with functions and variables.
Function `import` has the following syntax:
```js
math.import(object: Object [, options: Object])
```
Where:
- `object` is an object or array containing the functions and/or values to be
imported. `import` support regular values and functions, typed functions
(see section [Typed functions](#typed-functions)), and factory functions
(see section [Factory functions](#factory-functions)).
An array is only applicable when it contains factory functions.
- `options` is an optional second argument with options.
The following options are available:
- `{boolean} override`
If `true`, existing functions will be overwritten. The default value is `false`.
- `{boolean} silent`
If `true`, the function will not throw errors on duplicates or invalid
types. Default value is `false`.
- `{boolean} wrap`
If `true`, the functions will be wrapped in a wrapper function which
converts data types like Matrix to primitive data types like Array.
The wrapper is needed when extending math.js with libraries which do not
support the math.js data types. The default value is `false`.
The following code example shows how to import a function and a value into math.js:
```js
// define new functions and variables
math.import({
myvalue: 42,
hello: function (name) {
return 'hello, ' + name + '!';
}
});
// defined functions can be used in both JavaScript as well as the parser
math.myvalue * 2; // 84
math.hello('user'); // 'hello, user!'
var parser = math.parser();
parser.eval('myvalue + 10'); // 52
parser.eval('hello("user")'); // 'hello, user!'
```
## Import external libraries
External libraries like
[numbers.js](https://github.com/sjkaliski/numbers.js) and
[numeric.js](http://numericjs.com/) can be imported as follows.
The libraries must be installed using npm:
$ npm install numbers
$ npm install numeric
The libraries can be easily imported into math.js using `import`.
In order to convert math.js specific data types like `Matrix` to primitive types
like `Array`, the imported functions can be wrapped by enabling `{wrap: true}`.
```js
// import the numbers.js and numeric.js libraries into math.js
math.import(require('numbers'), {wrap: true, silent: true});
math.import(require('numeric'), {wrap: true, silent: true});
// use functions from numbers.js
math.fibonacci(7); // 13
math.eval('fibonacci(7)'); // 13
// use functions from numeric.js
math.eval('eig([1, 2; 4, 3])').lambda.x; // [5, -1]
```
## Typed functions
Typed functions can be created using `math.typed`. A typed function is a function
which does type checking on the input arguments. It can have multiple signatures.
And can automatically convert input types where needed.
A typed function can be created like:
```js
var max = typed('max', {
'number, number': function (a, b) {
return Math.max(a, b);
},
'BigNumber, BigNumber': function (a, b) {
return a.greaterThan(b) ? a : b;
}
});
```
Typed functions can be merged as long as there are no conflicts in the signatures.
This allows for extending existing functions in math.js with support for new
data types.
```js
// create a new data type
function MyType (value) {
this.value = value;
}
MyType.prototype.isMyType = true;
MyType.prototype.toString = function () {
return 'MyType:' + this.value;
}
// define a new datatype
math.typed.addType({
name: 'MyType',
test: function (x) {
// test whether x is of type MyType
return x && x.isMyType;
}
})
// use the type in a new typed function
var add = typed('add', {
'MyType, MyType': function (a, b) {
return new MyType(a.value + b.value);
}
});
// import in math.js, extend the existing function `add` with support for MyType
math.import({add: add});
// use the new type
var ans = math.add(new MyType(2), new MyType(3)); // returns MyType(5)
console.log(ans); // outputs 'MyType:5'
```
Detailed information on typed functions is available here:
[https://github.com/josdejong/typed-function](https://github.com/josdejong/typed-function)
## Factory functions
Regular JavaScript functions can be imported in math.js using `math.import`:
```js
math.import({
myFunction: function (a, b) {
// ...
}
});
```
The function can be stored in a separate file:
```js
exports.myFunction = function (a, b) {
// ...
}
```
Which can be imported like:
```js
math.import(require('./myFunction.js'));
```
An issue arises when `myFunction` needs functionality from math.js:
it doesn't have access to the current instance of math.js when in a separate file.
Factory functions can be used to solve this issue. A file exporting a factory function
looks like:
```js
exports.name = 'myFunction';
exports.factory = function (type, config, load, typed) {
return myFunction (a, b) {
// ...
}
};
```
The file exports a name and a factory function. When running `math.import`, the factory
function is invoked by math.js with four arguments:
- `type: Object`: Object containing the data types of math.js,
like `type.BigNumber` and `type.Unit`.
- `config: Object`: object with the configuration of math.js.
- `load: function`: loader function to access functions from math.js. For example to
load the function `add`:
```js
exports.factory = function (type, config, load, typed) {
var add = load(require('mathjs/lib/function/arithmetic/add'));
return myFunction (a, b) {
// ...
}
};
```
- `typed: function`: function to create typed-functions.
The result returned by a factory function will be imported into the `math`
namespace under the given `name`, `math.myFunction` in the above example.
A factory can contain the following properties:
- `name: string`. The name of the exported function or value. Required.
- `factory: function (type, config, load, typed) `. The factory function,
must return the function or value to be imported in math.js. Required.
- `path: string`. An optional path to where the function or value will be
imported. By default, imported functions have no path and are imported in
the 'flat' namespace `math`. Data types have `type` as path, and will be
located under `math.type.*`. Optional.
- `lazy: boolean`. If true (default), the factory function will be lazy loaded:
it is executed as soon as the function is about to be used.
- `math: boolean`. False by default. If true, the `math` namespace is passed
to the factory function as fifth argument. Should not be used unless there
is a very good reason for it.
To import a set of factory functions, the function `math.import` accepts an
array containing factory functions:
```js
math.import([
require('./myFactoryFunction1.js'),
require('./myFactoryFunction2.js'),
require('./myFactoryFunction3.js'),
// ...
]);
```

View File

@@ -0,0 +1,21 @@
# Core
## Usage
The core of math.js is the `math` namespace containing all functions and constants. There are three ways to do calculations in math.js:
- Doing regular function calls like `math.add(math.sqrt(4), 2)`.
- Evaluating expressions like `math.eval('sqrt(4) + 2')`
- Chaining operations like `math.chain(4).sqrt().add(2)`.
## Configuration
math.js can be configured using the `math.config()`, see page [Configuration](configuration.md).
## Extension
math.js can be extended with new functions and constants using the function `math.import()`, see page [Extension](extension.md).
## Serialization
To persist or exchange data structures like matrices and units, the data types of math.js can be stringified as JSON. This is explained on the page [Serialization](serialization.md).

View File

@@ -0,0 +1,38 @@
# Serialization
Math.js has a number of data types like `Matrix`, `Complex`, and `Unit`. These
types are instantiated JavaScript objects. To be able to store these data types
or send them between processes, they must be serialized. The data types of
math.js can be serialized to JSON. Use cases:
- Store data in a database or on disk.
- Interchange of data between a server and a client.
- Interchange of data between a web worker and the browser.
Math.js types can be serialized using JavaScript's built-in `JSON.stringify`
function:
```js
var x = math.complex('2 + 3i');
var str = JSON.stringify(x);
console.log(str);
// outputs a string '{"mathjs":"Complex","re":2,"im":3}'
```
In order to deserialize a string, containing math.js data types, `JSON.parse`
can be used. In order to recognize the data types of math.js, `JSON.parse` must
be called with the reviver function of math.js:
```js
var json = '{"mathjs":"Unit","value":5,"unit":"cm","fixPrefix":false}';
var x = JSON.parse(json, math.json.reviver); // Unit 5 cm
```
Note that if math.js is used in conjunction with other data types, it is
possible to use multiple reviver functions at the same time by cascading them:
```js
var reviver = function (key, value) {
return reviver1(key, reviver2(key, value));
}
```

View File

@@ -0,0 +1,72 @@
# Custom bundling
Math.js is a large library containing many data types and functions.
It is well possible that you only need a small portion of the library.
Math.js allows for creating a custom index file, loading only the data types
and functions that you need. This give faster load times, and allows bundling
only the used part of the library with tools like Webpack or browserify.
To load an empty instance of math.js, load `mathjs/core`. This core only
contains functions `import` and `config`.
```js
// Load the math.js core
var core = require('mathjs/core');
// Create a new, empty math.js instance
// It will only contain methods `import` and `config`
var math = core.create();
```
Then, use `math.import` to load the needed data types and functions.
It's important to load the data types first, and after that load functions
and constants. The functions are dynamically built, depending on the available
data types.
```js
// load the data types you need. Let's say you just want to use fractions,
// but no matrices, complex numbers, bignumbers, and other stuff.
//
// To load all data types:
//
// math.import(require('mathjs/lib/type'));
//
math.import(require('mathjs/lib/type/fraction'));
// Load the functions you need.
//
// To load all functions:
//
// math.import(require('mathjs/lib/function'));
//
// To load all functions of a specific category:
//
// math.import(require('mathjs/lib/function/arithmetic'));
//
math.import(require('mathjs/lib/function/arithmetic/add'));
math.import(require('mathjs/lib/function/arithmetic/subtract'));
math.import(require('mathjs/lib/function/arithmetic/multiply'));
math.import(require('mathjs/lib/function/arithmetic/divide'));
math.import(require('mathjs/lib/function/string/format'));
```
To see which data types and categories are available, explore the `index.js`
files in the folder `./lib`.
The imported functions and data types can now be used:
```js
// Use the loaded functions
var a = math.fraction(1, 3);
var b = math.fraction(3, 7);
var c = math.add(a, b);
console.log('result:', math.format(c)); // outputs "result: 16/21"
```
Suppose the custom loading code (loading `mathjs/core` and doing the imports)
is located in a file `custom_loading.js`. It's now possible to bundle
this file using for example browserify:
```bash
$ browserify custom_loading.js -o custom_loading.bundle.js
```

View File

@@ -0,0 +1,102 @@
# BigNumbers
For calculations with an arbitrary precision, math.js supports a `BigNumber`
datatype. BigNumber support is powered by
[decimal.js](https://github.com/MikeMcl/decimal.js/).
## Usage
A BigNumber can be created using the function `bignumber`:
```js
math.bignumber('2.3e+500'); // BigNumber, 2.3e+500
```
Most functions can determine the type of output from the type of input:
a number as input will return a number as output, a BigNumber as input returns
a BigNumber as output. Functions which cannot determine the type of output
from the input (for example `math.eval`) use the default number type `number`,
which can be configured when instantiating math.js. To configure the use of
BigNumbers instead of [numbers](numbers.md) by default, configure math.js like:
```js
math.config({
number: 'BigNumber', // Default type of number:
// 'number' (default), 'BigNumber', or 'Fraction'
precision: 64 // Number of significant digits for BigNumbers
});
// use math
math.eval('0.1 + 0.2'); // BigNumber, 0.3
```
The default precision for BigNumber is 64 digits, and can be configured with
the option `precision`.
## Support
Most functions in math.js support BigNumbers, but not all of them.
For example the function `random` doesn't support BigNumbers.
## Round-off errors
Calculations with BigNumber are much slower than calculations with Number,
but they can be executed with an arbitrary precision. By using a higher
precision, it is less likely that round-off errors occur:
```js
// round-off errors with numbers
math.add(0.1, 0.2); // Number, 0.30000000000000004
math.divide(0.3, 0.2); // Number, 1.4999999999999998
// no round-off errors with BigNumbers :)
math.add(math.bignumber(0.1), math.bignumber(0.2)); // BigNumber, 0.3
math.divide(math.bignumber(0.3), math.bignumber(0.2)); // BigNumber, 1.5
```
## Limitations
It's important to realize that BigNumbers do not solve *all* problems related
to precision and round-off errors. Numbers with an infinite number of digits
cannot be represented with a regular number nor a BigNumber. Though a BigNumber
can store a much larger number of digits, the amount of digits remains limited
if only to keep calculations fast enough to remain practical.
```js
var one = math.bignumber(1);
var three = math.bignumber(3);
var third = math.divide(one, three);
console.log(third.toString());
// outputs 0.3333333333333333333333333333333333333333333333333333333333333333
var ans = math.multiply(third, three);
console.log(ans.toString());
// outputs 0.9999999999999999999999999999999999999999999999999999999999999999
// this should be 1 again, but `third` is rounded to a limited number of digits 3
```
## Conversion
BigNumbers can be converted to numbers and vice versa using the functions
`number` and `bignumber`. When converting a BigNumber to a number, the high
precision of the BigNumber will be lost. When a BigNumber is too large to be represented
as Number, it will be initialized as `Infinity`.
```js
// converting numbers and BigNumbers
var a = math.number(0.3); // number, 0.3
var b = math.bignumber(a); // BigNumber, 0.3
var c = math.number(b); // number, 0.3
// exceeding the maximum of a number
var d = math.bignumber('1.2e500'); // BigNumber, 1.2e+500
var e = math.number(d); // number, Infinity
// loosing precision when converting to number
var f = math.bignumber('0.2222222222222222222'); // BigNumber, 0.2222222222222222222
var g = math.number(f); // number, 0.2222222222222222
```

View File

@@ -0,0 +1,123 @@
# Complex Numbers
Math.js supports the creation, manipulation, and calculations with complex numbers.
Support of complex numbers is powered by the library [complex.js](https://github.com/infusion/Complex.js).
In mathematics, a complex number is an expression of the form `a + bi`,
where `a` and `b` are real numbers and `i` represents the imaginary number
defined as `i^2 = -1`. (In other words, `i` is the square root of `-1`.)
The real number `a` is called the real part of the complex number,
and the real number `b` is the imaginary part. For example, `3 + 2i` is a
complex number, having real part `3` and imaginary part `2`.
Complex numbers are often used in applied mathematics, control theory,
signal analysis, fluid dynamics and other fields.
## Usage
A complex number is created using the function `math.complex`. This function
accepts:
- two numbers representing the real and imaginary part of the value,
- a single string containing a complex value in the form `a + bi` where `a`
and `b` respectively represent the real and imaginary part of the complex number.
- an object with either properties `re` and `im` for the real and imaginary
part of the value, or two properties `r` and `phi` containing the polar
coordinates of a complex value.
The function returns a `Complex` object.
Syntax:
```js
math.complex(re: number) : Complex
math.complex(re: number, im: number) : Complex
math.complex(complex: Complex) : Complex
math.complex({re: Number, im: Number}) : Complex
math.complex({r: number, phi: number}) : Complex
math.complex(str: string) : Complex
```
Examples:
```js
var a = math.complex(2, 3); // Complex 2 + 3i
a.re; // Number 2
a.im; // Number 3
var b = math.complex('4 - 2i'); // Complex 4 - 2i
b.re = 5; // Number 5
b; // Complex 5 - 2i
```
## Calculations
Most functions of math.js support complex numbers. Complex and real numbers
can be used together.
```js
var a = math.complex(2, 3); // Complex 2 + 3i
var b = math.complex('4 - 2i'); // Complex 4 - 2i
math.re(a); // Number 2
math.im(a); // Number 3
math.conj(a); // Complex 2 - 3i
math.add(a, b); // Complex 6 + i
math.multiply(a, 2); // Complex 4 + 6i
math.sqrt(-4); // Complex 2i
```
## API
A `Complex` object contains the following properties and functions:
### complex.re
A number containing the real part of the complex number. Can be read and replaced.
### complex.im
A number containing the imaginary part of the complex number. Can be read and replaced.
### complex.clone()
Create a clone of the complex number.
### complex.equals(other)
Test whether a complex number equals another complex value.
Two complex numbers are equal when both their real and imaginary parts are
equal.
### complex.format([precision: number])
Get a string representation of the complex number,
formatted as `a + bi` where `a` is the real part and `b` the imaginary part.
If precision is defined, the units value will be rounded to the provided
number of digits.
### complex.fromJSON(json)
Revive a complex number from a JSON object. Accepts
An object `{mathjs: 'Complex', re: number, im: number}`, where the property
`mathjs` is optional.
Used when deserializing a complex number, see [Serialization](../core/serialization.md).
### complex.fromPolar(r: number, phi: number)
Create a complex number from polar coordinates.
### complex.toJSON()
Returns a JSON representation of the complex number, with signature
`{mathjs: 'Complex', re: number, im: number}`.
Used when serializing a complex number, see [Serialization](../core/serialization.md).
### complex.toPolar()
Get the polar coordinates of the complex number, returns
an object with properties `r` and `phi`.
### complex.toString()
Returns a string representation of the complex number, formatted
as `a + bi` where `a` is the real part and `b` the imaginary part.

View File

@@ -0,0 +1,75 @@
# Fractions
For calculations with fractions, math.js supports a `Fraction` data type.
Fraction support is powered by [fraction.js](https://github.com/infusion/Fraction.js).
Unlike [numbers](numbers.md) and [BigNumbers](./bignumbers.md), fractions can
store numbers with infinitely repeating decimals, for example `1/3 = 0.3333333...`,
which can be represented as `0.(3)`, or `2/7` which can be represented as `0.(285714)`.
## Usage
A Fraction can be created using the function `fraction`:
```js
math.fraction('1/3'); // Fraction, 1/3
math.fraction(2, 3); // Fraction, 2/3
math.fraction('0.(3)'); // Fraction, 1/3
```
And can be used in functions like `add` and `multiply` like:
```js
math.add(math.fraction('1/3'), math.fraction('1/6')); // Fraction, 1/2
math.multiply(math.fraction('1/4'), math.fraction('1/2')); // Fraction, 1/8
```
Note that not all functions support fractions. For example trigonometric
functions doesn't support fractions. When not supported, the functions
will convert the input to numbers and return a number as result.
Most functions will determine the type of output from the type of input:
a number as input will return a number as output, a Fraction as input returns
a Fraction as output. Functions which cannot determine the type of output
from the input (for example `math.eval`) use the default number type `number`,
which can be configured when instantiating math.js. To configure the use of
fractions instead of [numbers](numbers.md) by default, configure math.js like:
```js
// Configure the default type of number: 'number' (default), 'BigNumber', or 'Fraction'
math.config({
number: 'Fraction'
});
// use the expression parser
math.eval('0.32 + 0.08'); // Fraction, 2/5
```
## Support
The following functions support fractions:
- Arithmetic functions: `abs`, `add`, `ceil`, `cube`, `divide`, `dotDivide`, `dotMultiply`, `fix`, `floor`, `gcd`, `mod`, `multiply`, `round`, `sign`, `square`, `subtract`, `unaryMinus`, `unaryPlus`.
- Construction functions: `fraction`.
- Relational functions: `compare`, `deepEqual`, `equal`, `larger`, `largerEq`, `smaller`, `smallerEq`, `unequal`.
- Utils functions: `format`.
## Conversion
Fractions can be converted to numbers and vice versa using the functions
`number` and `fraction`. When converting a Fraction to a number, precision
may be lost when the value cannot represented in 16 digits.
```js
// converting numbers and fractions
var a = math.number(0.3); // number, 0.3
var b = math.fraction(a); // Fraction, 3/10
var c = math.number(b); // number, 0.3
// loosing precision when converting to number: a fraction can represent
// a number with an infinite number of repeating decimals, a number just
// stores about 16 digits and cuts consecutive digits.
var d = math.fraction('2/5'); // Fraction, 2/5
var e = math.number(d); // number, 0.4
```

View File

@@ -0,0 +1,67 @@
# Data Types
The functions of math.js support multiple data types, both native JavaScript
types as well as more advanced types implemented in math.js. The data types can
be mixed together in calculations, for example by adding a Number to a
Complex number or Array.
The supported data types are:
- Boolean
- [Number](numbers.md)
- [BigNumber](bignumbers.md)
- [Complex](complex_numbers.md)
- [Fraction](fractions.md)
- [Array](matrices.md)
- [Matrix](matrices.md)
- [Unit](units.md)
- String
Function [`math.typeof(x)`](../reference/functions/typeof.md) can be used to get
the type of a variable.
Example usage:
```js
// use numbers
math.subtract(7.1, 2.3); // 4.8
math.round(math.pi, 3); // 3.142
math.sqrt(4.41e2); // 21
// use BigNumbers
math.add(math.bignumber(0.1), math.bignumber(0.2)); // BigNumber, 0.3
// use Fractions
math.add(math.fraction(1), math.fraction(3)); // Fraction, 0.(3)
// use strings
math.add('hello ', 'world'); // 'hello world'
math.max('A', 'D', 'C'); // 'D'
// use complex numbers
var a = math.complex(2, 3); // 2 + 3i
a.re; // 2
a.im; // 3
var b = math.complex('4 - 2i'); // 4 - 2i
math.add(a, b); // 6 + i
math.sqrt(-4); // 2i
// use arrays
var array = [1, 2, 3, 4, 5];
math.factorial(array); // Array, [1, 2, 6, 24, 120]
math.add(array, 3); // Array, [3, 5, 6, 7, 8]
// use matrices
var matrix = math.matrix([1, 4, 9, 16, 25]); // Matrix, [1, 4, 9, 16, 25]
math.sqrt(matrix); // Matrix, [1, 2, 3, 4, 5]
// use units
var a = math.unit(55, 'cm'); // 550 mm
var b = math.unit('0.1m'); // 100 mm
math.add(a, b); // 0.65 m
// check the type of a variable
math.typeof(2); // 'number'
math.typeof(math.unit('2 inch')); // 'Unit'
math.typeof(math.sqrt(-4)); // 'Complex'
```

View File

@@ -0,0 +1,343 @@
# Matrices
Math.js supports multi dimensional matrices and arrays. Matrices can be
created, manipulated, and used in calculations. Both regular JavaScript
arrays as well as the matrix type implemented by math.js can be used
interchangeably in all relevant math.js functions. math.js supports both
dense and sparse matrices.
## Arrays and matrices
Math.js supports two types of matrices:
- `Array`, a regular JavaScript array. A multi dimensional array can be created
by nesting arrays.
- `Matrix`, a matrix implementation by math.js. A `Matrix` is an object wrapped
around a regular JavaScript `Array`, providing utility functions for easy
matrix manipulation such as `subset`, `size`, `resize`, `clone`, and more.
In most cases, the type of matrix output from functions is determined by the
function input: An `Array` as input will return an `Array`, a `Matrix` as input
will return a `Matrix`. In case of mixed input, a `Matrix` is returned.
For functions where the type of output cannot be determined from the
input, the output is determined by the configuration option `matrix`,
which can be a string `'Matrix'` (default) or `'Array'`.
```js
// create an array and a matrix
var array = [[2, 0], [-1, 3]]; // Array
var matrix = math.matrix([[7, 1], [-2, 3]]); // Matrix
// perform a calculation on an array and matrix
math.square(array); // Array, [[4, 0], [1, 9]]
math.square(matrix); // Matrix, [[49, 1], [4, 9]]
// perform calculations with mixed array and matrix input
math.add(array, matrix); // Matrix, [[9, 1], [-3, 6]]
math.multiply(array, matrix); // Matrix, [[14, 2], [-13, 8]]
// create a matrix. Type of output of function ones is determined by the
// configuration option `matrix`
math.ones(2, 3); // Matrix, [[1, 1, 1], [1, 1, 1]]
```
## Creation
A matrix can be created from an array using the function `math.matrix`. The
provided array can contain nested arrays in order to create a multi-dimensional matrix. When called without arguments, an empty matrix will be
created.
```js
// create matrices
math.matrix(); // Matrix, size [0]
math.matrix([0, 1, 2]); // Matrix, size [3]
math.matrix([[0, 1], [2, 3], [4, 5]]); // Matrix, size [3, 2]
```
Math.js supports regular Arrays. Multiple dimensions can be created
by nesting Arrays in each other.
```js
// create arrays
[]; // Array, size [0]
[0, 1, 2] ; // Array, size [3]
[[0, 1], [2, 3], [4, 5]]; // Array, size [3, 2]
```
Matrices can contain different types of values: numbers, complex numbers,
units, or strings. Different types can be mixed together in a single matrix.
```js
// create a matrix with mixed types
var a = math.matrix([2.3, 'hello', math.complex(3, -4), math.unit('5.2 mm')]);
a.subset(math.index(1)); // 'hello'
```
There are a number of functions to create a matrix with a specific size and
content: `ones`, `zeros`, `eye`.
```js
// zeros creates a matrix filled with zeros
math.zeros(3); // Matrix, size [3], [0, 0, 0]
math.zeros(3, 2); // Matrix, size [3, 2], [[0, 0], [0, 0], [0, 0]]
math.zeros(2, 2, 2); // Matrix, size [2, 2, 2],
// [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
// ones creates a matrix filled with ones
math.ones(3); // Matrix, size [3], [1, 1, 1]
math.multiply(math.ones(2, 2), 5); // Matrix, size [2, 2], [[5, 5], [5, 5]]
// eye creates an identity matrix
math.eye(3); // Matrix, size [3, 3], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
math.eye(2, 3); // Matrix, size [2, 3], [[1, 0, 0], [0, 1, 0]]
```
The functions `ones`, `zeros`, and `eye` also accept a single array
or matrix containing the dimensions for the matrix. When the input is an Array,
the functions will output an Array. When the input is a Matrix, the output will
be a Matrix. Note that in case of numbers as arguments, the output is
determined by the option `matrix` as discussed in section
[Arrays and matrices](#arrays-and-matrices).
```js
// Array as input gives Array as output
math.ones([2, 3]); // Array, size [3, 2], [[1, 1, 1], [1, 1, 1]]
math.ones(math.matrix([2, 3])); // Matrix, size [3, 2], [[1, 1, 1], [1, 1, 1]]
```
Ranges can be created using the function `range`. The function `range` is
called with parameters start and end, and optionally a parameter step.
The start of the range is included, the end of the range is excluded.
```js
math.range(0, 4); // [0, 1, 2, 3]
math.range(0, 8, 2); // [0, 2, 4, 6]
math.range(3, -1, -1); // [3, 2, 1, 0]
```
## Calculations
All relevant functions of math.js support matrices and arrays.
```js
// perform a calculation on a matrix
var a = math.matrix([1, 4, 9, 16, 25]); // Matrix, [1, 4, 9, 16, 25]
math.sqrt(a); // Matrix, [1, 2, 3, 4, 5]
// perform a calculation on an array
var b = [1, 2, 3, 4, 5];
math.factorial(b); // Array, [1, 2, 6, 24, 120]
// multiply an array with a matrix
var c = [[2, 0], [-1, 3]]; // Array
var d = math.matrix([[7, 1], [-2, 3]]); // Matrix
math.multiply(c, d); // Matrix, [[14, 2], [-13, 8]]
// add a number to a matrix
math.add(c, 2); // Array, [[4, 2], [1, 5]]
// calculate the determinant of a matrix
math.det(c); // 6
math.det(d); // 23
```
## Size and Dimensions
Math.js uses geometric dimensions:
- A scalar is zero-dimensional.
- A vector is one-dimensional.
- A matrix is two or multi-dimensional.
The size of a matrix can be calculated with the function `size`. Function `size`
returns a `Matrix` or `Array`, depending on the configuration option `matrix`.
Furthermore, matrices have a function `size` as well, which always returns
an Array.
```js
// get the size of a scalar
math.size(2.4); // Matrix, []
math.size(math.complex(3, 2)); // Matrix, []
math.size(math.unit('5.3 mm')); // Matrix, []
// get the size of a one-dimensional matrix (a vector) and a string
math.size([0, 1, 2, 3]); // Array, [4]
math.size('hello world'); // Matrix, [11]
// get the size of a two-dimensional matrix
var a = [[0, 1, 2, 3]]; // Array
var b = math.matrix([[0, 1, 2], [3, 4, 5]]); // Matrix
math.size(a); // Array, [1, 4]
math.size(b); // Matrix, [2, 3]
// matrices have a function size (always returns an Array)
b.size(); // Array, [2, 3]
// get the size of a multi-dimensional matrix
var c = [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]];
math.size(c); // Array, [2, 2, 3]
```
## Resizing
Matrices can be resized using their `resize` function. This function is called
with an Array with the new size as the first argument, and accepts an optional
default value. If no default value is provided, new entries will be filled with
zero. To leave new entries uninitialized, specify `math.uninitialized` as the
default value.
```js
var a = math.matrix(); // Matrix, size [0], []
a.resize([2, 3]); // Matrix, size [2, 3], [[0, 0, 0], [0, 0, 0]]
a.resize([2, 2, 2]); // Matrix, size [2, 2, 2],
// [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
var b = math.matrix();
b.resize([3], 7); // Matrix, size [3], [7, 7, 7]
b.resize([5], 9); // Matrix, size [5], [7, 7, 7, 9, 9]
b.resize([2]); // Matrix, size [2], [7, 7]
```
Outer dimensions of a matrix can be squeezed using the function `squeeze`. When
getting or setting a subset in a matrix, the subset is automatically squeezed
or unsqueezed.
```js
// squeeze a matrix
var a = [[[0, 1, 2]]];
math.squeeze(a); // [0, 1, 2]
math.squeeze([[3]]); // 3
// subsets are automatically squeezed
var b = math.matrix([[0, 1], [2, 3]]);
b.subset([1, 0]); // 2
```
## Getting or replacing subsets
Subsets of a matrix can be retrieved or replaced using the function `subset`.
Matrices have a `subset` function, which is applied to the matrix itself:
`Matrix.subset(index [, replacement])`. For both matrices and arrays,
the static function `subset(matrix, index [, replacement])` can be used.
When parameter `replacement` is provided, the function will replace a subset
in the matrix, and if not, a subset of the matrix will be returned.
A subset can be defined using an `Index`. An `Index` contains a single value
or a set of values for each dimension of a matrix. An `Index` can be
created using the function `index`.
Matrix indexes in math.js are zero-based, like most programming languages
including JavaScript itself.
Note that mathematical applications like Matlab and Octave work differently,
as they use one-based indexes.
```js
// create some matrices
var a = [0, 1, 2, 3];
var b = [[0, 1], [2, 3]];
var c = math.zeros(2, 2);
var d = math.matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]]);
var e = math.matrix();
// get a subset
math.subset(a, math.index(1)); // 1
math.subset(a, math.index([2, 3])); // Array, [2, 3]
math.subset(a, math.index(math.range(0,4))); // Array, [0, 1, 2, 3]
math.subset(b, math.index(1, 0)); // 2
math.subset(b, math.index(1, [0, 1])); // Array, [2, 3]
math.subset(b, math.index([0, 1], 0)); // Matrix, [[0], [2]]
// get a subset
d.subset(math.index([1, 2], [0, 1])); // Matrix, [[3, 4], [6, 7]]
d.subset(math.index(1, 2)); // 5
// replace a subset. The subset will be applied to a clone of the matrix
math.subset(b, math.index(1, 0), 9); // Array, [[0, 1], [9, 3]]
math.subset(b, math.index(2, [0, 1]), [4, 5]);// Array, [[0, 1], [2, 3], [4, 5]]
// replace a subset. The subset will be applied to the matrix itself
c.subset(math.index(0, 1),1); // Matrix, [[0, 1], [0, 0]]
c.subset(math.index(1, [0, 1]), [2, 3]); // Matrix, [[0, 1], [2, 3]]
e.resize([2, 3], 0); // Matrix, [[0, 0, 0], [0, 0, 0]]
e.subset(math.index(1, 2), 5); // Matrix, [[0, 0, 0], [0, 0, 5]]
```
## Iterating
Matrices contain functions `map` and `forEach` to iterate over all elements of
the (multidimensional) matrix. The callback function of `map` and `forEach` has
three parameters: `value` (the value of the currently iterated element),
`index` (an array with the index value for each dimension), and `matrix` (the
matrix being iterated). This syntax is similar to the `map` and `forEach`
functions of native JavaScript Arrays, except that the index is no number but
an Array with numbers for each dimension.
```js
var a = math.matrix([[0, 1], [2, 3], [4, 5]]);
// The iteration below will output the following in the console:
// value: 0 index: [0, 0]
// value: 1 index: [0, 1]
// value: 2 index: [1, 0]
// value: 3 index: [1, 1]
// value: 4 index: [2, 0]
// value: 5 index: [2, 1]
a.forEach(function (value, index, matrix) {
console.log('value:', value, 'index:', index);
});
// Apply a transformation on the matrix
var b = a.map(function (value, index, matrix) {
return math.multiply(math.sin(value), math.exp(math.abs(value)));
});
console.log(b.format(5)); // [[0, 2.2874], [6.7188, 2.8345], [-41.32, -142.32]]
// Create a matrix with the cumulative of all elements
var count = 0;
var cum = a.map(function (value, index, matrix) {
count += value;
return count;
});
console.log(cum.toString()); // [[0, 1], [3, 6], [10, 15]]
```
## Storage types
Math.js supports both dense matrices as well as sparse matrices. Sparse matrices are efficient for matrices largely containing zeros. In that case they save a lot of memory, and calculations can be much faster than for dense matrices.
Math.js supports two type of matrices:
- Dense matrix (`'dense'`, `default`) A regular, dense matrix, supporting multi-dimensional matrices. This is the default matrix type.
- Sparse matrix (`'sparse'`): A two dimensional sparse matrix implementation.
The type of matrix can be selected when creating a matrix using the construction functions `matrix`, `diag`, `eye`, `ones`, and `zeros`.
```js
// create sparse matrices
var m1 = math.matrix([[0, 1], [0, 0]], 'sparse');
var m2 = math.eye(1000, 1000, 'sparse');
```
## API
All relevant functions in math.js support Matrices and Arrays. Functions like `math.add` and `math.subtract`, `math.sqrt` handle matrices element wise. There is a set of functions specifically for creating or manipulating matrices, such as:
- Functions like `math.matrix` and `math.sparse`, `math.ones`, `math.zeros`, and `math.eye` to create a matrix.
- Functions like `math.subset` and `math.index` to get or replace a part of a matrix
- Functions like `math.transpose` and `math.diag` to manipulate matrices.
A full list of matrix functions is available on the [functions reference page](../reference/functions.md#matrix-functions).
Two types of matrix classes are available in math.js, for storage of dense and sparse matrices. Although they contain public functions documented as follows, using the following API directly is *not* recommended. Prefer using the functions in the "math" namespace wherever possible.
- [DenseMatrix](../reference/classes/densematrix.md)
- [SparseMatrix](../reference/classes/sparsematrix.md)

View File

@@ -0,0 +1,106 @@
# Numbers
Math.js supports three types of numbers:
- Number for fast floating point arithmetic, described on this page.
- BigNumber for arbitrary precision arithmetic, described on the page
[BigNumbers](bignumbers.md).
- Fraction, which stores numbers in terms of a numerator and denominators,
described on the page [Fractions](fractions.md).
## Configuration
Most functions can determine the type of output from the type of input:
a number as input will return a number as output, a BigNumber as input returns
a BigNumber as output. Functions which cannot determine the type of output
from the input (for example `math.eval`) use the default number type, which
can be configured when instantiating math.js:
```js
math.config({
number: 'number' // Default type of number:
// 'number' (default), 'BigNumber', or 'Fraction'
});
```
## Round-off errors
Math.js uses the built-in JavaScript Number type. A Number is a floating point
number with a limited precision of 64 bits, about 16 digits. The largest integer
number which can be represented by a JavaScript Number
is `+/- 9007199254740992` (`+/- 2^53`). Because of the limited precision of
floating point numbers round-off errors can occur during calculations.
This can be easily demonstrated:
```js
// a round-off error
0.1 + 0.2; // 0.30000000000000004
math.add(0.1, 0.2); // 0.30000000000000004
```
In most cases, round-off errors don't matter: they have no significant
impact on the results. However, it looks ugly when displaying output to a user.
A solution is to limit the precision just below the actual precision of 16
digits in the displayed output:
```js
// prevent round-off errors showing up in output
var ans = math.add(0.1, 0.2); // 0.30000000000000004
math.format(ans, {precision: 14}); // '0.3'
```
Alternatives are to use [Fractions](fractions.md) which store a number as a numerator and denominator, or [BigNumbers](bignumbers.md), which store a number with a higher precision.
## Minimum and maximum
A Number can store values between `5e-324` and `1.7976931348623157e+308`.
Values smaller than the minimum are stored as `0`, and values larger than the
maximum are stored as `+/- Infinity`.
```js
// exceeding the maximum and minimum number
console.log(1e309); // Infinity
console.log(1e-324); // 0
```
## Equality
Because of rounding errors in calculations, it is unsafe to compare JavaScript
Numbers. For example executing `0.1 + 0.2 == 0.3` in JavaScript will return
false, as the addition `0.1 + 0.2` introduces a round-off error and does not
return exactly `0.3`.
To solve this problem, the relational functions of math.js check whether the
relative difference between the compared values is smaller than the configured
option `epsilon`. In pseudo code (without exceptions for 0, Infinity and NaN):
diff = abs(x - y)
nearlyEqual = (diff <= max(abs(x), abs(y)) * EPSILON) OR (diff < DBL_EPSILON)
where:
- `EPSILON` is the relative difference between x and y. Epsilon is configurable
and is `1e-14` by default. See [Configuration](../core/configuration.md).
- `DBL_EPSILON` is the minimum positive floating point number such that
`1.0 + DBL_EPSILON != 1.0`. This is a constant with a value of approximately
`2.2204460492503130808472633361816e-16`;
Note that the relational functions cannot be used to compare small values
(`< 2.22e-16`). These values are all considered equal to zero.
Examples:
```js
// compare values having a round-off error
console.log(0.1 + 0.2 == 0.3); // false
console.log(math.equal(0.1 + 0.2, 0.3)); // true
// small values (< 2.22e-16) cannot be compared
console.log(3e-20 == 3.1e-20); // false
console.log(math.equal(3e-20, 3.1e-20)); // true
```
The available relational functions are: `compare`, `equal`, `larger`,
`largerEq`, `smaller`, `smallerEq`, `unequal`.

View File

@@ -0,0 +1,424 @@
# Units
Math.js supports units. Units can be used to do calculations and to perform
conversions.
## Usage
Units can be created using the function `math.unit`. This function accepts
either a single string argument containing a value and unit, or two arguments,
the first being a numeric value and the second a string containing a unit.
Most units support prefixes like `k` or `kilo`, and many units have both a
full name and an abbreviation. The returned object is a `Unit`.
Syntax:
```js
math.unit(value: number, name: string) : Unit
math.unit(unit: string) : Unit
math.unit(unit: Unit) : Unit
```
Example usage:
```js
var a = math.unit(45, 'cm'); // Unit 450 mm
var b = math.unit('0.1 kilogram'); // Unit 100 gram
var c = math.unit('2 inch'); // Unit 2 inch
var d = math.unit('90 km/h'); // Unit 90 km/h
var e = math.unit('101325 kg/(m s^2)'); // Unit 101325 kg / (m s^2)
```
```js
var a = math.unit(55, 'cm'); // Unit 550 mm
var b = math.unit('0.1 kilogram'); // Unit 100 gram
var c = math.unit('2 inch'); // Unit 100 millimeter
var d = c.to('cm'); // Unit 5.08 cm
b.toNumber('gram'); // Number 100
math.number(b, 'gram'); // Number 100
c.equals(a); // false
c.equals(d); // true
c.equalBase(a); // true
c.equalBase(b); // false
d.toString(); // String "5.08 cm"
```
Use care when creating a unit with multiple terms in the denominator. Implicit multiplication has the same operator precedence as explicit multiplication and division, which means these three expressions are identical:
```js
// These three are identical
var correct1 = math.unit('8.314 m^3 Pa / mol / K'); // Unit 8.314 (m^3 Pa) / (mol K)
var correct2 = math.unit('8.314 (m^3 Pa) / (mol K)'); // Unit 8.314 (m^3 Pa) / (mol K)
var correct3 = math.unit('8.314 (m^3 * Pa) / (mol * K)'); // Unit 8.314 (m^3 Pa) / (mol K)
```
But this expression, which omits the second `/` between `mol` and `K`, results in the wrong value:
```js
// Missing the second '/' between 'mol' and 'K'
var incorrect = math.unit('8.314 m^3 Pa / mol K'); // Unit 8.314 (m^3 Pa K) / mol
```
## Calculations
The operations that support units are `add`, `subtract`, `multiply`, `divide`, `pow`, `abs`, `sqrt`, `square`, `cube`, and `sign`.
Trigonometric functions like `cos` are also supported when the argument is an angle.
```js
var a = math.unit(45, 'cm'); // Unit 450 mm
var b = math.unit('0.1m'); // Unit 100 mm
math.add(a, b); // Unit 0.65 m
math.multiply(b, 2); // Unit 200 mm
var c = math.unit(45, 'deg'); // Unit 45 deg
math.cos(c); // Number 0.7071067811865476
// Kinetic energy of average sedan on highway
var d = math.unit('80 mi/h') // Unit 80 mi/h
var e = math.unit('2 tonne') // Unit 2 tonne
var f = math.multiply(0.5, math.multipy(math.pow(d, 2), e));
// 1.2790064742399996 MJ
```
Operations with arrays are supported too:
```js
// Force on a charged particle moving through a magnetic field
var B = math.eval('[1, 0, 0] T'); // [1 T, 0 T, 0 T]
var v = math.eval('[0, 1, 0] m/s'); // [0 m / s, 1 m / s, 0 m / s]
var q = math.eval('1 C'); // 1 C
var F = math.multiply(q, math.cross(v, B)); // [0 N, 0 N, -1 N]
```
All arithmetic operators act on the value of the unit as it is represented in SI units.
This may lead to surprising behavior when working with temperature scales like `celsius` (or `degC`) and `fahrenheit` (or `degF`).
In general you should avoid calculations using `celsius` and `fahrenheit`. Rather, use `kelvin` (or `K`) and `rankine` (or `R`) instead.
This example highlights some problems when using `celsius` and `fahrenheit` in calculations:
```js
var T_14F = math.unit('14 degF'); // Unit 14 degF (263.15 K)
var T_28F = math.multiply(T1, 2); // Unit 487.67 degF (526.3 K), not 28 degF
var Tnegative = math.unit(-13, 'degF'); // Unit -13 degF (248.15 K)
var Tpositive = math.abs(T1); // Unit -13 degF (248.15 K), not 13 degF
var Trate1 = math.eval('5 (degC/hour)'); // Unit 5 degC/hour
var Trate2 = math.eval('(5 degC)/hour'); // Unit 278.15 degC/hour
```
The expression parser supports units too. This is described in the section about
units on the page [Syntax](../expressions/syntax.md#units).
## User-Defined Units
You can add your own units to Math.js using the `math.createUnit` function. The following example defines a new unit `furlong`, then uses the user-defined unit in a calculation:
```js
math.createUnit('furlong', '220 yards');
math.eval('1 mile to furlong'); // 8 furlong
```
If you cannot express the new unit in terms of any existing unit, then the second argument can be omitted. In this case, a new base unit is created:
```js
// A 'foo' cannot be expressed in terms of any other unit.
math.createUnit('foo');
math.eval('8 foo * 4 feet'); // 32 foo feet
```
The second argument to `createUnit` can also be a configuration object consisting of the following properties:
* **definition** A `string` or `Unit` which defines the user-defined unit in terms of existing built-in or user-defined units. If omitted, a new base unit is created.
* **prefixes** A `string` indicating which prefixes math.js should use with the new unit. Possible values are `'none'`, `'short'`, `'long'`, `'binary_short'`, or `'binary_long'`. Default is `'none'`.
* **offset** A value applied when converting to the unit. This is very helpful for temperature scales that do not share a zero with the absolute temperature scale. For example, if we were defining fahrenheit for the first time, we would use: `math.createUnit('fahrenheit', {definition: '0.555556 kelvin', offset: 459.67})`
* **aliases** An array of strings to alias the new unit. Example: `math.createUnit('knot', {definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts']})`
An optional `options` object can also be supplied as the last argument to `createUnits`. Currently only the `override` option is supported:
```js
// Redefine the mile (would not be the first time in history)
math.createUnit('mile', '1609.347218694', {override: true}});
```
Base units created without specifying a definition cannot be overridden.
Multiple units can defined using a single call to `createUnit` by passing an object map as the first argument, where each key in the object is the name of a new unit and the value is either a string defining the unit, or an object with the configuration properties listed above. If the value is an empty string or an object lacking a definition property, a new base unit is created.
For example:
```js
math.createUnit( {
foo: {
prefixes: 'long'
},
bar: '40 foo',
baz: {
definition: '1 bar/hour',
prefixes: 'long'
}
},
{
override: true
});
math.eval('50000 kilofoo/s'); // 4.5 gigabaz
```
### Return Value
`createUnit` returns the created unit, or, when multiple units are created, the last unit created. Since `createUnit` is also compatible with the expression parser, this allows you to do things like this:
```js
math.eval('45 mile/hour to createUnit("knot", "0.514444m/s")')
// 39.103964668651976 knot
```
## API
A `Unit` object contains the following functions:
### unit.clone()
Clone the unit, returns a new unit with the same parameters.
### unit.equalBase(unit)
Test whether a unit has the same base as an other unit:
length, mass, etc.
### unit.equals(unit)
Test whether a unit equals an other unit. Units are equal
when they have the same base and same value when normalized to SI units.
### unit.format([precision])
Get a string representation of the unit. The function
will determine the best fitting prefix for the unit. If precision is defined,
the units value will be rounded to the provided number of digits.
### unit.fromJSON(json)
Revive a unit from a JSON object. Accepts
An object `{mathjs: 'Unit', value: number, unit: string, fixPrefix: boolean}`,
where the property `mathjs` and `fixPrefix` are optional.
Used when deserializing a unit, see [Serialization](../core/serialization.md).
### unit.splitUnit(parts)
Split a unit into the specified parts. For example:
```js
var u = math.unit(1, 'm');
u.splitUnit(['ft', 'in']); // 3 feet,3.3700787401574765 inch
```
### unit.to(unitName)
Convert the unit to a specific unit name. Returns a clone of
the unit with a fixed prefix and unit.
### unit.toJSON()
Returns a JSON representation of the unit, with signature
`{mathjs: 'Unit', value: number, unit: string, fixPrefix: boolean}`.
Used when serializing a unit, see [Serialization](../core/serialization.md).
### unit.toNumber(unitName)
Get the value of a unit when converted to the
specified unit (a unit with optional prefix but without value).
The type of the returned value is always `number`.
### unit.toNumeric(unitName)
Get the value of a unit when converted to the
specified unit (a unit with optional prefix but without value).
The type of the returned value depends on how the unit was created and
can be `number`, `Fraction`, or `BigNumber`.
### unit.toString()
Get a string representation of the unit. The function will
determine the best fitting prefix for the unit.
## Unit reference
This section lists all available units, prefixes, and physical constants. These can be used via the Unit object, or via `math.eval()`.
## Reference
Math.js comes with the following built-in units.
Base | Unit
------------------- | ---
Length | meter (m), inch (in), foot (ft), yard (yd), mile (mi), link (li), rod (rd), chain (ch), angstrom, mil
Surface area | m2, sqin, sqft, sqyd, sqmi, sqrd, sqch, sqmil, acre, hectare
Volume | m3, litre (l, L, lt, liter), cc, cuin, cuft, cuyd, teaspoon, tablespoon
Liquid volume | minim (min), fluiddram (fldr), fluidounce (floz), gill (gi), cup (cp), pint (pt), quart (qt), gallon (gal), beerbarrel (bbl), oilbarrel (obl), hogshead, drop (gtt)
Angles | rad (radian), deg (degree), grad (gradian), cycle, arcsec (arcsecond), arcmin (arcminute)
Time | second (s, secs, seconds), minute (mins, minutes), hour (h, hr, hrs, hours), day (days), week (weeks), month (months), year (years), decade (decades), century (centuries), millennium (millennia)
Frequency | hertz (Hz)
Mass | gram(g), tonne, ton, grain (gr), dram (dr), ounce (oz), poundmass (lbm, lb, lbs), hundredweight (cwt), stick, stone
Electric current | ampere (A)
Temperature | kelvin (K), celsius (degC), fahrenheit (degF), rankine (degR)
Amount of substance | mole (mol)
Luminous intensity | candela (cd)
Force | newton (N), dyne (dyn), poundforce (lbf), kip
Energy | joule (J), erg, Wh, BTU, electronvolt (eV)
Power | watt (W), hp
Pressure | Pa, psi, atm, torr, bar, mmHg, mmH2O, cmH2O
Electricity and magnetism | ampere (A), coulomb (C), watt (W), volt (V), ohm, farad (F), weber (Wb), tesla (T), henry (H), siemens (S), electronvolt (eV)
Binary | bit (b), byte (B)
Note: all time units are based on the Julian year, with one month being 1/12th of a Julian year, a year being one Julian year, a decade being 10 Julian years, a century being 100, and a millennium being 1000.
Note that all relevant units can also be written in plural form, for example `5 meters` instead of `5 meter` or `10 seconds` instead of `10 second`.
Surface and volume units can alternatively be expressed in terms of length units raised to a power, for example `100 in^2` instead of `100 sqin`.
### Prefixes
The following decimal prefixes are available.
Name | Abbreviation | Value
------- | ------------- | -----
deca | da | 1e1
hecto | h | 1e2
kilo | k | 1e3
mega | M | 1e6
giga | G | 1e9
tera | T | 1e12
peta | P | 1e15
exa | E | 1e18
zetta | Z | 1e21
yotta | Y | 1e24
Name | Abbreviation | Value
------ | ------------- | -----
deci | d | 1e-1
centi | c | 1e-2
milli | m | 1e-3
micro | u | 1e-6
nano | n | 1e-9
pico | p | 1e-12
femto | f | 1e-15
atto | a | 1e-18
zepto | z | 1e-21
yocto | y | 1e-24
The following binary prefixes are available.
They can be used with units `bit` (`b`) and `byte` (`B`).
Name | Abbreviation | Value
---- | ------------ | -----
kibi | Ki | 1024
mebi | Mi | 1024^2
gibi | Gi | 1024^3
tebi | Ti | 1024^4
pebi | Pi | 1024^5
exi | Ei | 1024^6
zebi | Zi | 1024^7
yobi | Yi | 1024^8
Name | Abbreviation | Value
----- | ------------ | -----
kilo | k | 1e3
mega | M | 1e6
giga | G | 1e9
tera | T | 1e12
peta | P | 1e15
exa | E | 1e18
zetta | Z | 1e21
yotta | Y | 1e24
### Physical Constants
Math.js includes the following physical constants. See [Wikipedia](http://en.wikipedia.org/wiki/Physical_constants) for more information.
#### Universal constants
Name | Symbol | Value | Unit
----------------------|--------------------------------------------------------|-------------------|-------------------------------------------------------
speedOfLight | <i>c</i> | 299792458 | m &#183; s<sup>-1</sup>
gravitationConstant | <i>G</i> | 6.6738480e-11 | m<sup>3</sup> &#183; kg<sup>-1</sup> &#183; s<sup>-2</sup>
planckConstant | <i>h</i> | 6.626069311e-34 | J &#183; s
reducedPlanckConstant | <i><span style="text-decoration:overline">h</span></i> | 1.05457172647e-34 | J &#183; s
#### Electromagnetic constants
Name | Symbol | Value | Unit
--------------------------|--------------------------------------------------|-----------------------|----------------------------------------
magneticConstant | <i>&mu;<sub>0</sub></i> | 1.2566370614e-6 | N &#183; A<sup>-2</sup>
electricConstant | <i>&epsilon;<sub>0</sub></i> | 8.854187817e-12 | F &#183; m<sup>-1</sup>
vacuumImpedance | <i>Z<sub>0</sub></i> | 376.730313461 | &ohm;
coulomb | <i>&kappa;</i> | 8.9875517873681764e9 | N &#183; m<sup>2</sup> &#183; C<sup>-2</sup>
elementaryCharge | <i>e</i> | 1.60217656535e-19 | C
bohrMagneton | <i>&mu;<sub>B</sub></i> | 9.2740096820e-24 | J &#183; T<sup>-1</sup>
conductanceQuantum | <i>G<sub>0</sub></i> | 7.748091734625e-5 | S
inverseConductanceQuantum | <i>G<sub>0</sub><sup>-1</sup></i> | 12906.403721742 | &ohm;
magneticFluxQuantum | <i><font face="Symbol">f</font><sub>0</sub></i> | 2.06783375846e-15 | Wb
nuclearMagneton | <i>&mu;<sub>N</sub></i> | 5.0507835311e-27 | J &#183; T<sup>-1</sup>
klitzing | <i>R<sub>K</sub></i> | 25812.807443484 | &ohm;
<!-- TODO: implement josephson
josephson | <i>K<sub>J</sub></i> | 4.8359787011e-14 | Hz &#183; V<sup>-1</sup>
-->
#### Atomic and nuclear constants
Name | Symbol | Value | Unit
------------------------|------------------------------|-----------------------|----------------------------------
bohrRadius | <i>a<sub>0</sub></i> | 5.291772109217e-11 | m
classicalElectronRadius | <i>r<sub>e</sub></i> | 2.817940326727e-15 | m
electronMass | <i>m<sub>e</sub></i> | 9.1093829140e-31 | kg
fermiCoupling | <i>G<sub>F</sub></i> | 1.1663645e-5 | GeV<sup>-2</sup>
fineStructure | <i>&alpha;</i> | 7.297352569824e-3 | -
hartreeEnergy | <i>E<abbr>h</abbr> </i> | 4.3597443419e-18 | J
protonMass | <i>m<sub>p</sub></i> | 1.67262177774e-27 | kg
deuteronMass | <i>m<sub>d</sub></i> | 3.3435830926e-27 | kg
neutronMass | <i>m<sub>n</sub></i> | 1.6749271613e-27 | kg
quantumOfCirculation | <i>h / (2m<sub>e</sub>)</i> | 3.636947552024e-4 | m<sup>2</sup> &#183; s<sup>-1</sup>
rydberg | <i>R<sub>&infin;</sub></i> | 10973731.56853955 | m<sup>-1</sup>
thomsonCrossSection | | 6.65245873413e-29 | m<sup>2</sup>
weakMixingAngle | | 0.222321 | -
efimovFactor | | 22.7 | -
#### Physico-chemical constants
Name | Symbol | Value | Unit
--------------------|------------------------------|---------------------|--------------------------------------------
atomicMass | <i>m<sub>u</sub></i> | 1.66053892173e-27 | kg
avogadro | <i>N<sub>A</sub></i> | 6.0221412927e23 | mol<sup>-1</sup>
boltzmann | <i>k</i> | 1.380648813e-23 | J &#183; K<sup>-1</sup>
faraday | <i>F</i> | 96485.336521 | C &#183; mol<sup>-1</sup>
firstRadiation | <i>c<sub>1</sub></i> | 3.7417715317e-16 | W &#183; m<sup>2</sup>
loschmidt | <i>n<sub>0</sub></i> | 2.686780524e25 | m<sup>-3</sup>
gasConstant | <i>R</i> | 8.314462175 | J &#183; K<sup>-1</sup> &#183; mol<sup>-1</sup>
molarPlanckConstant | <i>N<sub>A</sub> &#183; h</i>| 3.990312717628e-10| J &#183; s &#183; mol<sup>-1</sup>
molarVolume | <i>V<sub>m</sub></i> | 2.241396820e-10 | m<sup>3</sup> &#183; mol<sup>-1</sup>
sackurTetrode | | -1.164870823 | -
secondRadiation | <i>c<sub>2</sub></i> | 1.438777013e-2 | m &#183; K
stefanBoltzmann | <i>&sigma;</i> | 5.67037321e-8 | W &#183; m<sup>-2</sup> &#183; K<sup>-4</sup>
wienDisplacement | <i>b</i> | 2.897772126e-3 | m &#183; K
<!-- TODO: implement spectralRadiance
spectralRadiance | <i>c<sub>1L</sub></i> | 1.19104286953e-16 | W &#183; m<sup>2</sup> &#183; sr<sup>-1</sup>
-->
Note that the values of `loschmidt` and `molarVolume` are at `T = 273.15 K` and `p = 101.325 kPa`.
The value of `sackurTetrode` is at `T = 1 K` and `p = 101.325 kPa`.
#### Adopted values
Name | Symbol | Value | Unit
--------------|------------------------------|---------|-------------------------
molarMass | <i>M<sub>u</sub></i> | 1e-3 | kg &#183; mol<sup>-1</sup>
molarMassC12 | <i>M(<sub>12</sub>C)</i> | 1.2e-2 | kg &#183; mol<sup>-1</sup>
gravity | <i>g<sub>n</sub></i> | 9.80665 | m &#183; s<sup>-2</sup>
atm | <i>atm</i> | 101325 | Pa
#### Natural units
Name | Symbol | Value | Unit
------------------|-----------------------|--------------------|-----
planckLength | <i>l<sub>P</sub></i> | 1.61619997e-35 | m
planckMass | <i>m<sub>P</sub></i> | 2.1765113e-8 | kg
planckTime | <i>t<sub>P</sub></i> | 5.3910632e-44 | s
planckCharge | <i>q<sub>P</sub></i> | 1.87554595641e-18 | C
planckTemperature | <i>T<sub>P</sub></i> | 1.41683385e+32 | K

View File

@@ -0,0 +1,3 @@
# Expressions
This page has been moved here: [Expressions](expressions/index.md).

View File

@@ -0,0 +1,59 @@
# Algebra (symbolic computation)
math.js has built-in support for symbolic computation ([CAS](https://www.wikiwand.com/en/Computer_algebra_system)). It can parse expressions into an expression tree and do algebraic operations like simplification and derivation on the tree.
> It's worth mentioning an excellent extension on math.js here: [mathsteps](https://github.com/socraticorg/mathsteps), a step-by-step math solver library that is focused on pedagogy (how best to teach). The math problems it focuses on are pre-algebra and algebra problems involving simplifying expressions.
## Simplify
The function [`math.simplify`](../reference/functions/simplify.md) simplifies an expression tree:
```js
// simplify an expression
console.log(math.simplify('3 + 2 / 4').toString()); // '7 / 2'
console.log(math.simplify('2x + 3x').toString()); // '5 * x'
console.log(math.simplify('x^2 + x + 3 + x^2').toString()); // '2 * x ^ 2 + x + 3'
console.log(math.simplify('x * y * -x / (x ^ 2)').toString()); // '-y'
```
The function accepts either a string or an expression tree (`Node`) as input, and outputs a simplified expression tree (`Node`). This node tree can be transformed and evaluated as described in detail on the page [Expression trees]('./expression_trees.md').
```js
// work with an expression tree, evaluate results
var f = math.parse('2x + x');
var simplified = math.simplify(f);
console.log(simplified.toString()); // '3 * x'
console.log(simplified.eval({x: 4})); // 12
```
For more details on the theory of expression simplification, see:
- [Strategies for simplifying math expressions (Stackoverflow)](http://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions)
- [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification)
## Derivative
The function [`math.derivative`](../reference/functions/derivative.md) finds the symbolic derivative of an expression:
```js
// calculate a derivative
console.log(math.derivative('2x^2 + 3x + 4', 'x').toString()); // '4 * x + 3'
console.log(math.derivative('sin(2x)', 'x').toString()); // '2 * cos(2 * x)'
```
Similar to the function `math.simplify`, `math.derivative` accepts either a string or an expression tree (`Node`) as input, and outputs a simplified expression tree (`Node`).
```js
// work with an expression tree, evaluate results
var h = math.parse('x^2 + x');
var x = math.parse('x');
var dh = math.derivative(h, x);
console.log(dh.toString()); // '2 * x + 1'
console.log(dh.eval({x: 3})); // '7'
```
The rules used by `math.derivative` can be found on Wikipedia:
- [Differentiation rules (Wikipedia)](http://en.wikipedia.org/wiki/Differentiation_rules)

View File

@@ -0,0 +1,376 @@
# Customization
Besides parsing and evaluating expressions, the expression parser supports
a number of features to customize processing and evaluation of expressions
and outputting expressions.
On this page:
- [Function transforms](#function-transforms)
- [Custom argument parsing](#custom-argument-parsing)
- [Custom LaTeX handlers](#custom-latex-handlers)
- [Custom LaTeX and string output](#custom-latex-and-string-output)
- [Customize supported characters](#customize-supported-characters)
## Function transforms
It is possible to preprocess function arguments and post process a functions
return value by writing a *transform* for the function. A transform is a
function wrapping around a function to be transformed or completely replaces
a function.
For example, the functions for math.js use zero-based matrix indices (as is
common in programing languages), but the expression parser uses one-based
indices. To enable this, all functions dealing with indices have a transform,
which changes input from one-based to zero-based, and transforms output (and
error message) from zero-based to one-based.
```js
// using plain JavaScript, indices are zero-based:
var a = [[1, 2], [3, 4]]; // a 2x2 matrix
math.subset(a, math.index(0, 1)); // returns 2
// using the expression parser, indices are transformed to one-based:
var a = [[1, 2], [3, 4]]; // a 2x2 matrix
var scope = {
a: a
};
math.eval('subset(a, index(1, 2))', scope); // returns 2
```
To create a transform for a function, the transform function must be attached
to the function as property `transform`:
```js
var math = require('../index');
// create a function
function addIt(a, b) {
return a + b;
}
// attach a transform function to the function addIt
addIt.transform = function (a, b) {
console.log('input: a=' + a + ', b=' + b);
// we can manipulate input here before executing addIt
var res = addIt(a, b);
console.log('result: ' + res);
// we can manipulate result here before returning
return res;
};
// import the function into math.js
math.import({
addIt: addIt
});
// use the function via the expression parser
console.log('Using expression parser:');
console.log('2+4=' + math.eval('addIt(2, 4)'));
// This will output:
//
// input: a=2, b=4
// result: 6
// 2+4=6
// when used via plain JavaScript, the transform is not invoked
console.log('');
console.log('Using plain JavaScript:');
console.log('2+4=' + math.addIt(2, 4));
// This will output:
//
// 6
```
Functions with a transform must be imported in the `math` namespace, as they
need to be processed at compile time. They are not supported when passed via a
scope at evaluation time.
## Custom argument parsing
The expression parser of math.js has support for letting functions
parse and evaluate arguments themselves, instead of calling them with
evaluated arguments. This is useful for example when creating a function
like `plot(f(x), x)` or `integrate(f(x), x, start, end)`, where some of the
arguments need to be processed in a special way. In these cases, the expression
`f(x)` will be evaluated repeatedly by the function, and `x` is not evaluated
but used to specify the variable looping over the function `f(x)`.
Functions having a property `rawArgs` with value `true` are treated in a special
way by the expression parser: they will be invoked with unevaluated arguments,
allowing the function to process the arguments in a customized way. Raw
functions are called as:
```
rawFunction(args: Node[], math: Object, scope: Object)
```
Where :
- `args` is an Array with nodes of the parsed arguments.
- `math` is the math namespace against which the expression was compiled.
- `scope` is the scope provided when evaluating the expression.
Raw functions must be imported in the `math` namespace, as they need to be
processed at compile time. They are not supported when passed via a scope
at evaluation time.
A simple example:
```js
function myFunction(args, math, scope) {
// get string representation of the arguments
var str = args.map(function (arg) {
return arg.toString();
})
// evaluate the arguments
var res = args.map(function (arg) {
return arg.compile().eval(scope);
});
return 'arguments: ' + str.join(',') + ', evaluated: ' + res.join(',');
}
// mark the function as "rawArgs", so it will be called with unevaluated arguments
myFunction.rawArgs = true;
// import the new function in the math namespace
math.import({
myFunction: myFunction
})
// use the function
math.eval('myFunction(2 + 3, sqrt(4))');
// returns 'arguments: 2 + 3, sqrt(4), evaluated: 5, 2'
```
## Custom LaTeX handlers
You can attach a `toTex` property to your custom functions before importing them to define their LaTeX output. This
`toTex` property can be a handler in the format described in the next section 'Custom LaTeX and String conversion'
or a template string similar to ES6 templates.
### Template syntax
- `${name}`: Gets replaced by the name of the function
- `${args}`: Gets replaced by a comma separated list of the arguments of the function.
- `${args[0]}`: Gets replaced by the first argument of a function
- `$$`: Gets replaced by `$`
#### Example
```js
var customFunctions = {
plus: function (a, b) {
return a + b;
},
minus: function (a, b) {
return a - b;
},
binom: function (n, k) {
return 1;
}
};
customFunctions.plus.toTex = '${args[0]}+${args[1]}'; //template string
customFunctions.binom.toTex = '\\mathrm{${name}}\\left(${args}\\right)'; //template string
customFunctions.minus.toTex = function (node, options) { //handler function
return node.args[0].toTex(options) + node.name + node.args[1].toTex(options);
};
math.import(customFunctions);
math.parse('plus(1,2)').toTex(); //'1+2'
math.parse('binom(1,2)').toTex(); // '\\mathrm{binom}\\left(1,2\\right)'
math.parse('minus(1,2)').toTex(); // '1minus2'
```
## Custom LaTeX and string output
All expression nodes have a method `toTex` and `toString` to output an expression respectively in LaTex format or as regular text .
The functions `toTex` and `toString` accept an `options` argument to customise output. This object is of the following form:
```js
{
parenthesis: 'keep', // parenthesis option
handler: someHandler, // handler to change the output
implicit: 'hide' // how to treat implicit multiplication
}
```
### Parenthesis
The `parenthesis` option changes the way parentheses are used in the output. There are three options available:
- `keep` Keep the parentheses from the input and display them as is. This is the default.
- `auto` Only display parentheses that are necessary. Mathjs tries to get rid of as much parentheses as possible.
- `all` Display all parentheses that are given by the structure of the node tree. This makes the output precedence unambiguous.
There's two ways of passing callbacks:
1. Pass an object that maps function names to callbacks. Those callbacks will be used for FunctionNodes with
functions of that name.
2. Pass a function to `toTex`. This function will then be used for every node.
```js
var expression = math.parse('(1+1+1)');
expression.toString(); //(1 + 1 + 1)
expression.toString({parenthesis: 'keep'}); //(1 + 1 + 1)
expression.toString({parenthesis: 'auto'}); //1 + 1 + 1
expression.toString({parenthesis: 'all'}); //(1 + 1) + 1
```
### Handler
You can provide the `toTex` and `toString` functions of an expression with your own custom handlers that override the internal behaviour. This is especially useful to provide LaTeX/string output for your own custom functions. This can be done in two ways:
1. Pass an object that maps function names to callbacks. Those callbacks will be used for FunctionNodes that contain functions with that name.
2. Pass a callback directly. This callback will run for every node, so you can replace the output of anything you like.
A callback function has the following form:
```js
var callback = function (node, options) {
...
}
```
Where `options` is the object passed to `toTex`/`toString`. Don't forget to pass this on to the child nodes, and `node` is a reference to the current node.
If a callback returns nothing, the standard output will be used. If your callback returns a string, this string will be used.
**Although the following examples use `toTex`, it works for `toString` in the same way**
#### Examples for option 1
```js
var customFunctions = {
binomial: function (n, k) {
//calculate n choose k
// (do some stuff)
return result;
}
};
var customLaTeX = {
'binomial': function (node, options) { //provide toTex for your own custom function
return '\\binom{' + node.args[0].toTex(options) + '}{' + node.args[1].toTex(options) + '}';
},
'factorial': function (node, options) { //override toTex for builtin functions
return 'factorial\\left(' + node.args[0] + '\\right)';
}
};
```
You can simply use your custom toTex functions by passing them to `toTex`:
```js
math.import(customFunctions);
var expression = math.parse('binomial(factorial(2),1)');
var latex = expression.toTex({handler: customLaTeX});
//latex now contains "\binom{factorial\\left(2\\right)}{1}"
```
#### Examples for option 2:
```js
var customLaTeX = function (node, options) {
if ((node.type === 'OperatorNode') && (node.fn === 'add')) {
//don't forget to pass the options to the toTex functions
return node.args[0].toTex(options) + ' plus ' + node.args[1].toTex(options);
}
else if (node.type === 'ConstantNode') {
if (node.value == 0) {
return '\\mbox{zero}';
}
else if (node.value == 1) {
return '\\mbox{one}';
}
else if (node.value == 2) {
return '\\mbox{two}';
}
else {
return node.value;
}
}
};
var expression = math.parse('1+2');
var latex = expression.toTex({handler: customLaTeX});
//latex now contains '\mbox{one} plus \mbox{two}'
```
Another example in conjunction with custom functions:
```js
var customFunctions = {
binomial: function (n, k) {
//calculate n choose k
// (do some stuff)
return result;
}
};
var customLaTeX = function (node, options) {
if ((node.type === 'FunctionNode') && (node.name === 'binomial')) {
return '\\binom{' + node.args[0].toTex(options) + '}{' + node.args[1].toTex(options) + '}';
}
};
math.import(customFunctions);
var expression = math.parse('binomial(2,1)');
var latex = expression.toTex({handler: customLaTeX});
//latex now contains "\binom{2}{1}"
```
### Implicit multiplication
You can change the way that implicit multiplication is converted to a string or LaTeX. The two options are `hide`, to not show a multiplication operator for implicit multiplication and `show` to show it.
Example:
```js
var node = math.parse('2a');
node.toString(); //'2 a'
node.toString({implicit: 'hide'}); //'2 a'
node.toString({implicit: 'show'}); //'2 * a'
node.toTex(); //'2~ a'
node.toTex({implicit: 'hide'}); //'2~ a'
node.toTex({implicit: 'show'}); //'2\\cdot a'
```
## Customize supported characters
It is possible to customize the characters allowed in symbols and digits.
The `parse` function exposes the following test functions:
- `math.expression.parse.isAlpha(c, cPrev, cNext)`
- `math.expression.parse.isWhitespace(c, nestingLevel)`
- `math.expression.parse.isDecimalMark(c, cNext)`
- `math.expression.parse.isDigitDot(c)`
- `math.expression.parse.isDigit(c)`
The exact signature and implementation of these functions can be looked up in
the [source code of the parser](https://github.com/josdejong/mathjs/blob/master/lib/expression/parse.js). The allowed alpha characters are described here: [Constants and variables](syntax.md#constants-and-variables).
For example, the `$` character is not supported by default. It can be enabled
by replacing the `isAlpha` function:
```js
var isAlphaOriginal = math.expression.parse.isAlpha;
math.expression.parse.isAlpha = function (c, cPrev, cNext) {
return isAlphaOriginal(c, cPrev, cNext) || (c === '$');
};
// now we can use the $ character in expressions
var result = math.eval('$foo', {$foo: 42}); // returns 42
console.log(result);
```

View File

@@ -0,0 +1,610 @@
# Expression trees
When parsing an expression via `math.parse(expr)`, math.js generates an
expression tree and returns the root node of the tree. An expression tree can
be used to analyze, manipulate, and evaluate expressions.
Example:
```js
var node = math.parse('sqrt(2 + x)');
```
In this case, the expression `sqrt(2 + x)` is parsed as:
```
FunctionNode sqrt
|
OperatorNode +
/ \
ConstantNode 2 x SymbolNode
```
Alternatively, this expression tree can be build by manually creating nodes:
```js
var node1 = new math.expression.node.ConstantNode(2);
var node2 = new math.expression.node.SymbolNode('x');
var node3 = new math.expression.node.OperatorNode('+', 'add', [node1, node2]);
var node4 = new math.expression.node.FunctionNode('sqrt', [node3]);
```
The resulting expression tree with root node `node4` is equal to the expression
tree generated by `math.parse('sqrt(2 + x)')`.
## API
### Methods
All nodes have the following methods:
- `clone() : Node`
Create a shallow clone of the node.
The node itself is cloned, its childs are not cloned.
- `cloneDeep() : Node`
Create a deep clone of the node.
Both the node as well as all its childs are cloned recursively.
- `compile() : Object`
Compile an expression into optimized JavaScript code. `compile` returns an
object with a function `eval([scope])` to evaluate. Example:
```js
var node = math.parse('2 + x'); // returns the root Node of an expression tree
var code = node.compile(); // returns {eval: function (scope) {...}}
var eval = code.eval({x: 3}); // returns 5
```
- `eval([scope]) : Object`
Compile and eval an expression, this is the equivalent of doing
`node.compile().eval(scope)`. Example:
```js
var node = math.parse('2 + x'); // returns the root Node of an expression tree
var eval = node.eval({x: 3}); // returns 5
```
- `equals(other: Node) : boolean`
Test whether this node equals an other node. Does a deep comparison of the
values of both nodes.
- `filter(callback: function) : Node[]`
Recursively filter nodes in an expression tree. The `callback` function is
called as `callback(node: Node, path: string, parent: Node) : boolean` for
every node in the tree, and must return a boolean. The function `filter`
returns an array with nodes for which the test returned true.
Parameter `path` is a string containing a relative JSON Path.
Example:
```js
var node = math.parse('x^2 + x/4 + 3*y');
var filtered = node.filter(function (node) {
return node.isSymbolNode && node.name == 'x';
});
// returns an array with two entries: two SymbolNodes 'x'
```
- `forEach(callback: function) : Node[]`
Execute a callback for each of the child nodes of this node. The `callback`
function is called as `callback(child: Node, path: string, parent: Node)`.
Parameter `path` is a string containing a relative JSON Path.
See also `traverse`, which is a recursive version of `forEach`.
Example:
```js
var node = math.parse('3 * x + 2');
node.forEach(function (node, path, parent) {
switch (node.type) {
case 'OperatorNode': console.log(node.type, node.op); break;
case 'ConstantNode': console.log(node.type, node.value); break;
case 'SymbolNode': console.log(node.type, node.name); break;
default: console.log(node.type);
}
});
// outputs:
// OperatorNode *
// ConstantNode 2
```
- `map(callback: function) : Node[]`
Transform a node. Creates a new Node having it's childs be the results of
calling the provided callback function for each of the childs of the original
node. The `callback` function is called as `callback(child: Node, path: string,
parent: Node)` and must return a Node. Parameter `path` is a string containing
a relative JSON Path.
See also `transform`, which is a recursive version of `map`.
- `toString(options: object) : string`
Get a string representation of the parsed expression. This is not exactly
the same as the original input. Example:
```js
var node = math.parse('3+4*2');
node.toString(); // returns '3 + (4 * 2)'
```
Information about the options in [Customization](customization.md#custom-latex-and-string-output).
- `toTex(options: object): string`
Get a [LaTeX](http://en.wikipedia.org/wiki/LaTeX) representation of the
expression. Example:
```js
var node = math.parse('sqrt(2/3)');
node.toTex(); // returns '\sqrt{\frac{2}{3}}'
```
Information about the options in [Customization](customization.md#custom-latex-and-string-output).
- `transform(callback: function)`
Recursively transform an expression tree via a transform function. Similar
to `Array.map`, but recursively executed on all nodes in the expression tree.
The callback function is a mapping function accepting a node, and returning
a replacement for the node or the original node. Function `callback` is
called as `callback(node: Node, path: string, parent: Node)` for every node
in the tree, and must return a `Node`. Parameter `path` is a string containing
a relative JSON Path.
For example, to replace all nodes of type `SymbolNode` having name 'x' with a
ConstantNode with value `3`:
```js
var node = math.parse('x^2 + 5*x');
var transformed = node.transform(function (node, path, parent) {
if (node.SymbolNode && node.name == 'x') {
return new math.expression.node.ConstantNode(3);
}
else {
return node;
}
});
transformed.toString(); // returns '(3 ^ 2) + (5 * 3)'
```
- `traverse(callback)`
Recursively traverse all nodes in a node tree. Executes given callback for
this node and each of its child nodes. Similar to `Array.forEach`, except
recursive.
The callback function is a mapping function accepting a node, and returning
a replacement for the node or the original node. Function `callback` is
called as `callback(node: Node, path: string, parent: Node)` for every node
in the tree. Parameter `path` is a string containing a relative JSON Path.
Example:
```js
var node = math.parse('3 * x + 2');
node.traverse(function (node, path, parent) {
switch (node.type) {
case 'OperatorNode': console.log(node.type, node.op); break;
case 'ConstantNode': console.log(node.type, node.value); break;
case 'SymbolNode': console.log(node.type, node.name); break;
default: console.log(node.type);
}
});
// outputs:
// OperatorNode +
// OperatorNode *
// ConstantNode 3
// SymbolNode x
// ConstantNode 2
```
### Properties
Each `Node` has the following properties:
- `comment: string`
A string holding a comment if there was any in the expression, or else the
string will be empty string. A comment can be attached to the root node of
an expression or to each of the childs nodes of a `BlockNode`.
- `isNode: true`
Is defined with value `true` on Nodes. Additionally, each type of node
adds it's own flag, for example a `SymbolNode` as has a property
`isSymbolNode: true`.
- `type: string`
The type of the node, for example `'SymbolNode'` in case of a `SymbolNode`.
## Nodes
math.js has the following types of nodes. All nodes are available at the
namespace `math.expression.node`.
### AccessorNode
Construction:
```
new AccessorNode(object: Node, index: IndexNode)
```
Properties:
- `object: Node`
- `index: IndexNode`
- `name: string` (read-only) The function or method name. Returns an empty string when undefined.
Examples:
```js
var node1 = math.parse('a[3]');
var object = new math.expression.node.SymbolNode('a');
var index = new math.expression.node.IndexNode([3]);
var node2 = new math.expression.node.AccessorNode(object, index);
```
### ArrayNode
Construction:
```
new ArrayNode(items: Node[])
```
Properties:
- `items: Node[]`
Examples:
```js
var node1 = math.parse('[1, 2, 3]');
var one = new math.expression.node.ConstantNode(1);
var two = new math.expression.node.ConstantNode(2);
var three = new math.expression.node.ConstantNode(3);
var node2 = new math.expression.node.ArrayNode([one, two, three]);
```
### AssignmentNode
Construction:
```
new AssignmentNode(object: SymbolNode, value: Node)
new AssignmentNode(object: SymbolNode | AccessorNode, index: IndexNode, value: Node)
```
Properties:
- `object: SymbolNode | AccessorNode`
- `index: IndexNode | null`
- `value: Node`
- `name: string` (read-only) The function or method name. Returns an empty string when undefined.
Examples:
```js
var node1 = math.parse('a = 3');
var object = new math.expression.node.SymbolNode('a');
var value = new math.expression.node.ConstantNode(3);
var node2 = new math.expression.node.AssignmentNode(object, value);
```
### BlockNode
A `BlockNode` is created when parsing a multi line expression like `a=2;b=3` or
`a=2\nb=3`. Evaluating a `BlockNode` returns a `ResultSet`. The results can be
retrieved via `ResultSet.entries` or `ResultSet.valueOf()`, which contains
an `Array` with the results of the visible lines (i.e. lines not ending with
a semicolon).
Construction:
```
block = new BlockNode(Array.<{node: Node} | {node: Node, visible: boolean}>)
```
Properties:
- `blocks: Array.<{node: Node, visible: boolean}>`
Examples:
```js
var block1 = math.parse('a=1; b=2; c=3');
var a = new math.expression.node.SymbolNode('a');
var one = new math.expression.node.ConstantNode(1);
var ass1 = new math.expression.node.AssignmentNode(a, one);
var b = new math.expression.node.SymbolNode('b');
var two = new math.expression.node.ConstantNode(2);
var ass2 = new math.expression.node.AssignmentNode(b, two);
var c = new math.expression.node.SymbolNode('c');
var three = new math.expression.node.ConstantNode(3);
var ass3 = new math.expression.node.AssignmentNode(c, three);
var block2 = new BlockNode([
{node: ass1, visible: false},
{node: ass2, visible: false},
{node: ass3, visible: true}
]);
```
### ConditionalNode
Construction:
```
new ConditionalNode(condition: Node, trueExpr: Node, falseExpr: Node)
```
Properties:
- `condition: Node`
- `trueExpr: Node`
- `falseExpr: Node`
Examples:
```js
var node1 = math.parse('a > 0 ? a : -a');
var a = new math.expression.node.SymbolNode('a');
var zero = new math.expression.node.ConstantNode(0);
var condition = new math.expression.node.OperatorNode('>', 'larger', [a, zero]);
var trueExpr = a;
var falseExpr = new math.expression.node.OperatorNode('-', 'unaryMinus', [a]);
var node2 = new math.expression.node.ConditionalNode(condition, trueExpr, falseExpr);
```
### ConstantNode
Construction:
```
new ConstantNode(value: * [, valueType: string])
```
Properties:
- `value: *`
- `valueType: string`
Examples:
```js
var node1 = math.parse('2.4');
var node2 = new math.expression.node.ConstantNode(2.4);
var node3 = new math.expression.node.ConstantNode('2.4', 'number');
```
### FunctionAssignmentNode
Construction:
```
new FunctionAssignmentNode(name: string, params: string[], expr: Node)
```
Properties:
- `name: string`
- `params: string[]`
- `expr: Node`
Examples:
```js
var node1 = math.parse('f(x) = x^2');
var x = new math.expression.node.SymbolNode('x');
var two = new math.expression.node.ConstantNode(2);
var expr = new math.expression.node.OperatorNode('^', 'pow', [x, 2]);
var node2 = new math.expression.node.FunctionAssignmentNode('f', ['x'], expr);
```
### FunctionNode
Construction:
```
new FunctionNode(fn: Node | string, args: Node[])
```
Properties:
- `fn: Node | string` (read-only) The object or function name which to invoke.
- `args: Node[]`
Examples:
```js
var node1 = math.parse('sqrt(4)');
var four = new math.expression.node.ConstantNode(4);
var node3 = new math.expression.node.FunctionNode(new SymbolNode('sqrt'), [four]);
```
### IndexNode
Construction:
```
new IndexNode(dimensions: Node[])
new IndexNode(dimensions: Node[], dotNotation: boolean)
```
Each dimension can be a single value, a range, or a property. The values of
indices are one-based, including range end.
An optional property `dotNotation` can be provided describing whether this index
was written using dot notation like `a.b`, or using bracket notation
like `a["b"]`. Default value is `false`. This information is used when
stringifying the IndexNode.
Properties:
- `dimensions: Node[]`
- `dotNotation: boolean`
Examples:
```js
var node1 = math.parse('A[1:3, 2]');
var A = new math.expression.node.SymbolNode('A');
var one = new math.expression.node.ConstantNode(1);
var two = new math.expression.node.ConstantNode(2);
var three = new math.expression.node.ConstantNode(3);
var range = new math.expression.node.RangeNode(one, three);
var index = new math.expression.node.IndexNode([range, two]);
var node2 = new math.expression.node.AccessNode(A, index);
```
### ObjectNode
Construction:
```
new ObjectNode(properties: Object.<string, Node>)
```
Properties:
- `properties: Object.<string, Node>`
Examples:
```js
var node1 = math.parse('{a: 1, b: 2, c: 3}');
var a = new math.expression.node.ConstantNode(1);
var b = new math.expression.node.ConstantNode(2);
var c = new math.expression.node.ConstantNode(3);
var node2 = new math.expression.node.ObjectNode({a: a, b: b, c: c});
```
### OperatorNode
Construction:
```
new OperatorNode(op: string, fn: string, args: Node[])
```
Properties:
- `op: string`
- `fn: string`
- `args: Node[]`
Examples:
```js
var node1 = math.parse('2.3 + 5');
var a = new math.expression.node.ConstantNode(2.3);
var b = new math.expression.node.ConstantNode(5);
var node2 = new math.expression.node.OperatorNode('+', 'add', [a, b]);
```
### ParenthesisNode
Construction:
```
new ParenthesisNode(content: Node)
```
Properties:
- `content: Node`
Examples:
```js
var node1 = math.parse('(1)');
var a = new math.expression.node.ConstantNode(1);
var node2 = new math.expression.node.ParenthesisNode(a);
```
### RangeNode
Construction:
```
new RangeNode(start: Node, end: Node [, step: Node])
```
Properties:
- `start: Node`
- `end: Node`
- `step: Node | null`
Examples:
```js
var node1 = math.parse('1:10');
var node2 = math.parse('0:2:10');
var zero = new math.expression.node.ConstantNode(0);
var one = new math.expression.node.ConstantNode(1);
var two = new math.expression.node.ConstantNode(2);
var ten = new math.expression.node.ConstantNode(10);
var node3 = new math.expression.node.RangeNode(one, ten);
var node4 = new math.expression.node.RangeNode(zero, ten, two);
```
### SymbolNode
Construction:
```
new SymbolNode(name: string)
```
Properties:
- `name: string`
Examples:
```js
var node = math.parse('x');
var x = new math.expression.node.SymbolNode('x');
```

View File

@@ -0,0 +1,20 @@
# Expressions
Math.js contains a flexible and easy to use expression parser.
The parser supports all data types, functions and constants available in math.js.
Whilst the math.js library is aimed at JavaScript developers, the expression
parser is aimed at end users: mathematicians, engineers, students, pupils.
The syntax of the expression parser differs from JavaScript and the low-level
math.js library.
This section is divided in the following pages:
- [Parsing and evaluation](parsing.md) describes how to parse and
evaluate expressions with math.js.
- [Syntax](syntax.md) describes how to write expressions.
- [Expression trees](expression_trees.md) explains how to parse an expression into an
expression tree, and use this to analyse and manipulate the expression.
- [Algebra](algebra.md) describing symbolic computation in math.js.
- [Customization](customization.md) describes how to customize processing and
evaluation of expressions.

View File

@@ -0,0 +1,207 @@
# Expression parsing and evaluation
Expressions can be parsed and evaluated in various ways:
- Using the function [`math.eval(expr [,scope])`](#eval).
- Using the function [`math.compile(expr)`](#compile).
- Using the function [`math.parse(expr)`](#parse).
- By creating a [parser](#parser), `math.parser()`, which contains a function
`eval` and keeps a scope with assigned variables in memory.
## Eval
Math.js comes with a function `math.eval` to evaluate expressions. Syntax:
```js
math.eval(expr)
math.eval(expr, scope)
math.eval([expr1, expr2, expr3, ...])
math.eval([expr1, expr2, expr3, ...], scope)
```
Function `eval` accepts a single expression or an array with
expressions as the first argument and has an optional second argument
containing a scope with variables and functions. The scope is a regular
JavaScript Object. The scope will be used to resolve symbols, and to write
assigned variables or function.
The following code demonstrates how to evaluate expressions.
```js
// evaluate expressions
math.eval('sqrt(3^2 + 4^2)'); // 5
math.eval('sqrt(-4)'); // 2i
math.eval('2 inch to cm'); // 5.08 cm
math.eval('cos(45 deg)'); // 0.7071067811865476
// provide a scope
var scope = {
a: 3,
b: 4
};
math.eval('a * b', scope); // 12
math.eval('c = 2.3 + 4.5', scope); // 6.8
scope.c; // 6.8
```
## Compile
Math.js contains a function `math.compile` which compiles expressions
into JavaScript code. This is a shortcut for first [parsing](#parse) and then
compiling an expression. The syntax is:
```js
math.compile(expr);
math.compile([expr1, expr2, expr3, ...]);
```
Function `compile` accepts a single expression or an array with
expressions as the argument. Function `compile` returns an object with a function
`eval([scope])`, which can be executed to evaluate the expression against an
(optional) scope:
```js
var code = math.compile(expr); // compile an expression
var result = code.eval([scope]); // evaluate the code with an optional scope
```
An expression needs to be compiled only once, after which the
expression can be evaluated repeatedly and against different scopes.
The optional scope is used to resolve symbols and to write assigned
variables or functions. Parameter `scope` is a regular Object.
Example usage:
```js
// parse an expression into a node, and evaluate the node
var code1 = math.compile('sqrt(3^2 + 4^2)');
code1.eval(); // 5
```
## Parse
Math.js contains a function `math.parse` to parse expressions into an
[expression tree](expression_trees.md). The syntax is:
```js
math.parse(expr)
math.parse([expr1, expr2, expr3, ...])
```
Function `parse` accepts a single expression or an array with
expressions as the argument. Function `parse` returns a the root node of the tree,
which can be successively compiled and evaluated:
```js
var node = math.parse(expr); // parse expression into a node tree
var code = node.compile(); // compile the node tree
var result = code.eval([scope]); // evaluate the code with an optional scope
```
The API of nodes is described in detail on the page
[Expression trees](expression_trees.md).
An expression needs to be parsed and compiled only once, after which the
expression can be evaluated repeatedly. On evaluation, an optional scope
can be provided, which is used to resolve symbols and to write assigned
variables or functions. Parameter `scope` is a regular Object.
Example usage:
```js
// parse an expression into a node, and evaluate the node
var node1 = math.parse('sqrt(3^2 + 4^2)');
var code1 = node1.compile();
code1.eval(); // 5
// provide a scope
var node2 = math.parse('x^a', scope);
var code2 = node2.compile();
var scope = {
x: 3,
a: 2
};
code2.eval(scope); // 9
// change a value in the scope and re-evaluate the node
scope.a = 3;
code2.eval(scope); // 27
```
Parsed expressions can be exported to text using `node.toString()`, and can
be exported to LaTeX using `node.toTex()`. The LaTeX export can be used to
pretty print an expression in the browser with a library like
[MathJax](http://www.mathjax.org/). Example usage:
```js
// parse an expression
var node = math.parse('sqrt(x/x+1)');
node.toString(); // returns 'sqrt((x / x) + 1)'
node.toTex(); // returns '\sqrt{ {\frac{x}{x} }+{1} }'
```
## Parser
In addition to the static functions [`math.eval`](#eval) and
[`math.parse`](#parse), math.js contains a parser with functions `eval` and
`parse`, which automatically keeps a scope with assigned variables in memory.
The parser also contains some convenience functions to get, set, and remove
variables from memory.
A parser can be created by:
```js
var parser = math.parser();
```
The parser contains the following functions:
- `clear()`
Completely clear the parser's scope.
- `eval(expr)`
Evaluate an expression. Returns the result of the expression.
- `get(name)`
Retrieve a variable or function from the parser's scope.
- `getAll()`
Retrieve a map with all defined a variables from the parser's scope.
- `remove(name)`
Remove a variable or function from the parser's scope.
- `set(name, value)`
Set a variable or function in the parser's scope.
The following code shows how to create and use a parser.
```js
// create a parser
var parser = math.parser();
// evaluate expressions
parser.eval('sqrt(3^2 + 4^2)'); // 5
parser.eval('sqrt(-4)'); // 2i
parser.eval('2 inch to cm'); // 5.08 cm
parser.eval('cos(45 deg)'); // 0.7071067811865476
// define variables and functions
parser.eval('x = 7 / 2'); // 3.5
parser.eval('x + 3'); // 6.5
parser.eval('f(x, y) = x^y'); // f(x, y)
parser.eval('f(2, 3)'); // 8
// get and set variables and functions
var x = parser.get('x'); // x = 7
var f = parser.get('f'); // function
var g = f(3, 3); // g = 27
parser.set('h', 500);
parser.eval('h / 2'); // 250
parser.set('hello', function (name) {
return 'hello, ' + name + '!';
});
parser.eval('hello("user")'); // "hello, user!"
// clear defined functions and variables
parser.clear();
```

View File

@@ -0,0 +1,599 @@
# Expression syntax
This page describes the syntax of expression parser of math.js. It describes
how to work with the available data types, functions, operators, variables,
and more.
## Differences from JavaScript
The expression parser of math.js is aimed at a mathematical audience,
not a programming audience. The syntax is similar to most calculators and
mathematical applications. This is close to JavaScript as well, though there
are a few important differences between the syntax of the expression parser and
the lower level syntax of math.js. Differences are:
- No need to prefix functions and constants with the `math.*` namespace,
you can just enter `sin(pi / 4)`.
- Matrix indexes are one-based instead of zero-based.
- There are index and range operators which allow more conveniently getting
and setting matrix indexes, like `A[2:4, 1]`.
- Both indexes and ranges and have the upper-bound included.
- There is a differing syntax for defining functions. Example: `f(x) = x^2`.
- There are custom operators like `x + y` instead of `add(x, y)`.
- Some operators are different. For example `^` is used for exponentiation,
not bitwise xor.
## Operators
The expression parser has operators for all common arithmetic operations such
as addition and multiplication. The expression parser uses conventional infix
notation for operators: an operator is placed between its arguments.
Round parentheses can be used to override the default precedence of operators.
```js
// use operators
math.eval('2 + 3'); // 5
math.eval('2 * 3'); // 6
// use parentheses to override the default precedence
math.eval('2 + 3 * 4'); // 14
math.eval('(2 + 3) * 4'); // 20
```
The following operators are available:
Operator | Name | Syntax | Associativity | Example | Result
----------- | ----------------------- | ---------- | ------------- | --------------------- | ---------------
`(`, `)` | Grouping | `(x)` | None | `2 * (3 + 4)` | `14`
`[`, `]` | Matrix, Index | `[...]` | None | `[[1,2],[3,4]]` | `[[1,2],[3,4]]`
`{`, `}` | Object | `{...}` | None | `{a: 1, b: 2}` | `{a: 1, b: 2}`
`,` | Parameter separator | `x, y` | Left to right | `max(2, 1, 5)` | `5`
`.` | Property accessor | `obj.prop` | Left to right | `obj={a: 12}; obj.a` | `12`
`;` | Statement separator | `x; y` | Left to right | `a=2; b=3; a*b` | `[6]`
`;` | Row separator | `[x; y]` | Left to right | `[1,2;3,4]` | `[[1,2],[3,4]]`
`\n` | Statement separator | `x \n y` | Left to right | `a=2 \n b=3 \n a*b` | `[2,3,6]`
`+` | Add | `x + y` | Left to right | `4 + 5` | `9`
`+` | Unary plus | `+y` | Right to left | `+4` | `4`
`-` | Subtract | `x - y` | Left to right | `7 - 3` | `4`
`-` | Unary minus | `-y` | Right to left | `-4` | `-4`
`*` | Multiply | `x * y` | Left to right | `2 * 3` | `6`
`.*` | Element-wise multiply | `x .* y` | Left to right | `[1,2,3] .* [1,2,3]` | `[1,4,9]`
`/` | Divide | `x / y` | Left to right | `6 / 2` | `3`
`./` | Element-wise divide | `x ./ y` | Left to right | `[9,6,4] ./ [3,2,2]` | `[3,3,2]`
`%`, `mod` | Modulus | `x % y` | Left to right | `8 % 3` | `2`
`^` | Power | `x ^ y` | Right to left | `2 ^ 3` | `8`
`.^` | Element-wise power | `x .^ y` | Right to left | `[2,3] .^ [3,3]` | `[9,27]`
`'` | Transpose | `y'` | Left to right | `[[1,2],[3,4]]'` | `[[1,3],[2,4]]`
`!` | Factorial | `y!` | Left to right | `5!` | `120`
`&` | Bitwise and | `x & y` | Left to right | `5 & 3` | `1`
`~` | Bitwise not | `~x` | Right to left | `~2` | `-3`
<code>&#124;</code> | Bitwise or | <code>x &#124; y</code> | Left to right | <code>5 &#124; 3</code> | `7`
<code>^&#124;</code> | Bitwise xor | <code>x ^&#124; y</code> | Left to right | <code>5 ^&#124; 2</code> | `6`
`<<` | Left shift | `x << y` | Left to right | `4 << 1` | `8`
`>>` | Right arithmetic shift | `x >> y` | Left to right | `8 >> 1` | `4`
`>>>` | Right logical shift | `x >>> y` | Left to right | `-8 >>> 1` | `2147483644`
`and` | Logical and | `x and y` | Left to right | `true and false` | `false`
`not` | Logical not | `not y` | Right to left | `not true` | `false`
`or` | Logical or | `x or y` | Left to right | `true or false` | `true`
`xor` | Logical xor | `x xor y` | Left to right | `true xor true` | `false`
`=` | Assignment | `x = y` | Right to left | `a = 5` | `5`
`?` `:` | Conditional expression | `x ? y : z` | Right to left | `15 > 100 ? 1 : -1` | `-1`
`:` | Range | `x : y` | Right to left | `1:4` | `[1,2,3,4]`
`to`, `in` | Unit conversion | `x to y` | Left to right | `2 inch to cm` | `5.08 cm`
`==` | Equal | `x == y` | Left to right | `2 == 4 - 2` | `true`
`!=` | Unequal | `x != y` | Left to right | `2 != 3` | `true`
`<` | Smaller | `x < y` | Left to right | `2 < 3` | `true`
`>` | Larger | `x > y` | Left to right | `2 > 3` | `false`
`<=` | Smallereq | `x <= y` | Left to right | `4 <= 3` | `false`
`>=` | Largereq | `x >= y` | Left to right | `2 + 4 >= 6` | `true`
## Precedence
The operators have the following precedence, from highest to lowest:
Operators | Description
--------------------------------- | --------------------
`(...)`<br>`[...]`<br>`{...}` | Grouping<br>Matrix<br>Object
`x(...)`<br>`x[...]`<br>`obj.prop`<br>`:`| Function call<br>Matrix index<br>Property accessor<br>Key/value separator
`'` | Matrix transpose
`!` | Factorial
`^`, `.^` | Exponentiation
`+`, `-`, `~`, `not` | Unary plus, unary minus, bitwise not, logical not
`x unit` | Unit
`*`, `/`, `.*`, `./`, `%`, `mod` | Multiply, divide, modulus, implicit multiply
`+`, `-` | Add, subtract
`:` | Range
`to`, `in` | Unit conversion
`<<`, `>>`, `>>>` | Bitwise left shift, bitwise right arithmetic shift, bitwise right logical shift
`==`, `!=`, `<`, `>`, `<=`, `>=` | Relational
`&` | Bitwise and
<code>^&#124;</code> | Bitwise xor
<code>&#124;</code> | Bitwise or
`and` | Logical and
`xor` | Logical xor
`or` | Logical or
`?`, `:` | Conditional expression
`=` | Assignment
`,` | Parameter and column separator
`;` | Row separator
`\n`, `;` | Statement separators
## Functions
Functions are called by entering their name, followed by zero or more
arguments enclosed by parentheses. All available functions are listed on the
page [Functions](../reference/functions.md).
```js
math.eval('sqrt(25)'); // 5
math.eval('log(1000, 3 + 7)'); // 4
math.eval('sin(pi / 4)'); // 0.7071067811865475
```
New functions can be defined using the `function` keyword. Functions can be
defined with multiple variables. Function assignments are limited: they can
only be defined on a single line.
```js
var parser = math.parser();
parser.eval('f(x) = x ^ 2 - 5');
parser.eval('f(2)'); // -1
parser.eval('f(3)'); // 4
parser.eval('g(x, y) = x ^ y');
parser.eval('g(2, 3)'); // 8
```
Math.js itself heavily uses typed functions, which ensure correct inputs and
throws meaningful errors when the input arguments are invalid. One can create
a [typed-function](https://github.com/josdejong/typed-function) in the
expression parser like:
```js
var parser = math.parser();
parser.eval('f = typed({"number": f(x) = x ^ 2 - 5})');
```
## Constants and variables
Math.js has a number of built-in constants such as `pi` and `e`.
All available constants are listed on he page
[Constants](../reference/constants.md).
```js
// use constants
math.eval('pi'); // 3.141592653589793
math.eval('e ^ 2'); // 7.3890560989306495
math.eval('log(e)'); // 1
math.eval('e ^ (pi * i) + 1'); // ~0 (Euler)
```
Variables can be defined using the assignment operator `=`, and can be used
like constants.
```js
var parser = math.parser();
// define variables
parser.eval('a = 3.4'); // 3.4
parser.eval('b = 5 / 2'); // 2.5
// use variables
parser.eval('a * b'); // 8.5
```
Variable names must:
- Begin with an "alpha character", which is:
- A latin letter (upper or lower case). Ascii: `a-z`, `A-Z`
- An underscore. Ascii: `_`
- A latin letter with accents. Unicode: `\u00C0` - `\u02AF`
- A greek letter. Unicode: `\u0370` - `\u03FF`
- A letter-like character. Unicode: `\u2100` - `\u214F`
- A mathematical alphanumeric symbol. Unicode: `\u{1D400}` - `\u{1D7FF}` excluding invalid code points
- Contain only alpha characters (above) and digits `0-9`
- Not be any of the following: `mod`, `to`, `in`, `and`, `xor`, `or`, `not`, `end`. It is possible to assign to some of these, but that's not recommended.
It is possible to customize the allowed alpha characters, see [Customize supported characters](customization.md#customize-supported-characters) for more information.
## Data types
The expression parser supports booleans, numbers, complex numbers, units,
strings, matrices, and objects.
### Booleans
Booleans `true` and `false` can be used in expressions.
```js
// use booleans
math.eval('true'); // true
math.eval('false'); // false
math.eval('(2 == 3) == false'); // true
```
Booleans can be converted to numbers and strings and vice versa using the
functions `number` and `boolean`, and `string`.
```js
// convert booleans
math.eval('number(true)'); // 1
math.eval('string(false)'); // "false"
math.eval('boolean(1)'); // true
math.eval('boolean("false")'); // false
```
### Numbers
The most important and basic data type in math.js are numbers. Numbers use a
point as decimal mark. Numbers can be entered with exponential notation.
Examples:
```js
// numbers in math.js
math.eval('2'); // 2
math.eval('3.14'); // 3.14
math.eval('1.4e3'); // 1400
math.eval('22e-3'); // 0.022
```
A number can be converted to a string and vice versa using the functions
`number` and `string`.
```js
// convert a string into a number
math.eval('number("2.3")'); // 2.3
math.eval('string(2.3)'); // "2.3"
```
Math.js uses regular JavaScript numbers, which are floating points with a
limited precision and limited range. The limitations are described in detail
on the page [Numbers](../datatypes/numbers.md).
```js
math.eval('1e-325'); // 0
math.eval('1e309'); // Infinity
math.eval('-1e309'); // -Infinity
```
When doing calculations with floats, one can very easily get round-off errors:
```js
// round-off error due to limited floating point precision
math.eval('0.1 + 0.2'); // 0.30000000000000004
```
When outputting results, the function `math.format` can be used to hide
these round-off errors when outputting results for the user:
```js
var ans = math.eval('0.1 + 0.2'); // 0.30000000000000004
math.format(ans, {precision: 14}); // "0.3"
```
### BigNumbers
Math.js supports BigNumbers for calculations with an arbitrary precision.
The pros and cons of Number and BigNumber are explained in detail on the page
[Numbers](../datatypes/numbers.md).
BigNumbers are slower but have a higher precision. Calculations with big
numbers are supported only by arithmetic functions.
BigNumbers can be created using the `bignumber` function:
```js
math.eval('bignumber(0.1) + bignumber(0.2)'); // BigNumber, 0.3
```
The default number type of the expression parser can be changed at instantiation
of math.js. The expression parser parses numbers as BigNumber by default:
```js
// Configure the type of number: 'number' (default), 'BigNumber', or 'Fraction'
math.config({number: 'BigNumber'});
// all numbers are parsed as BigNumber
math.eval('0.1 + 0.2'); // BigNumber, 0.3
```
BigNumbers can be converted to numbers and vice versa using the functions
`number` and `bignumber`. When converting a BigNumber to a Number, the high
precision of the BigNumber will be lost. When a BigNumber is too large to be represented
as Number, it will be initialized as `Infinity`.
### Complex numbers
Complex numbers can be created using the imaginary unit `i`, which is defined
as `i^2 = -1`. Complex numbers have a real and complex part, which can be
retrieved using the functions `re` and `im`.
```js
var parser = math.parser();
// create complex numbers
parser.eval('a = 2 + 3i'); // Complex, 2 + 3i
parser.eval('b = 4 - i'); // Complex, 4 - i
// get real and imaginary part of a complex number
parser.eval('re(a)'); // Number, 2
parser.eval('im(a)'); // Number, 3
// calculations with complex numbers
parser.eval('a + b'); // Complex, 6 + 2i
parser.eval('a * b'); // Complex, 11 + 10i
parser.eval('i * i'); // Number, -1
parser.eval('sqrt(-4)'); // Complex, 2i
```
Math.js does not automatically convert complex numbers with an imaginary part
of zero to numbers. They can be converted to a number using the function
`number`.
```js
// convert a complex number to a number
var parser = math.parser();
parser.eval('a = 2 + 3i'); // Complex, 2 + 3i
parser.eval('b = a - 3i'); // Complex, 2 + 0i
parser.eval('number(b)'); // Number, 2
parser.eval('number(a)'); // Error: 2 + i is no valid number
```
### Units
math.js supports units. Units can be used in the arithmetic operations
add, subtract, multiply, divide, and exponentiation.
Units can also be converted from one to another.
An overview of all available units can be found on the page
[Units](../datatypes/units.md).
Units can be converted using the operator `to` or `in`.
```js
// create a unit
math.eval('5.4 kg'); // Unit, 5.4 kg
// convert a unit
math.eval('2 inch to cm'); // Unit, 5.08 cm
math.eval('20 celsius in fahrenheit'); // Unit, ~68 fahrenheit
math.eval('90 km/h to m/s'); // Unit, 25 m / s
// convert a unit to a number
// A second parameter with the unit for the exported number must be provided
math.eval('number(5 cm, mm)'); // Number, 50
// calculations with units
math.eval('0.5kg + 33g'); // Unit, 0.533 kg
math.eval('3 inch + 2 cm'); // Unit, 3.7874 inch
math.eval('3 inch + 2 cm'); // Unit, 3.7874 inch
math.eval('12 seconds * 2'); // Unit, 24 seconds
math.eval('sin(45 deg)'); // Number, 0.7071067811865475
math.eval('9.81 m/s^2 * 5 s to mi/h') // Unit, 109.72172512527 mi / h
```
### Strings
Strings are enclosed by double quotes ". Strings can be concatenated using the
function `concat` (not by adding them using `+` like in JavaScript). Parts of
a string can be retrieved or replaced by using indexes. Strings can be converted
to a number using function `number`, and numbers can be converted to a string
using function `string`.
When setting the value of a character in a string, the character that has been
set is returned. Likewise, when a range of characters is set, that range of
characters is returned.
```js
var parser = math.parser();
// create a string
parser.eval('"hello"'); // String, "hello"
// string manipulation
parser.eval('a = concat("hello", " world")'); // String, "hello world"
parser.eval('size(a)'); // Matrix [11]
parser.eval('a[1:5]'); // String, "hello"
parser.eval('a[1] = "H"'); // String, "H"
parser.eval('a[7:12] = "there!"'); // String, "there!"
parser.eval('a'); // String, "Hello there!"
// string conversion
parser.eval('number("300")'); // Number, 300
parser.eval('string(300)'); // String, "300"
```
Strings can be used in the `eval` function, to parse expressions inside
the expression parser:
```js
math.eval('eval("2 + 3")'); // 5
```
### Matrices
Matrices can be created by entering a series of values between square brackets,
elements are separated by a comma `,`.
A matrix like `[1, 2, 3]` will create a vector, a 1-dimensional matrix with
size `[3]`. To create a multi-dimensional matrix, matrices can be nested into
each other. For easier creation of two-dimensional matrices, a semicolon `;`
can be used to separate rows in a matrix.
```js
// create a matrix
math.eval('[1, 2, 3]'); // Matrix, size [3]
math.eval('[[1, 2, 3], [4, 5, 6]]'); // Matrix, size [2, 3]
math.eval('[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]'); // Matrix, size [2, 2, 2]
// create a two dimensional matrix
math.eval('[1, 2, 3; 4, 5, 6]'); // Matrix, size [2, 3]
```
Another way to create filled matrices is using the functions `zeros`, `ones`,
`eye`, and `range`.
```js
// initialize a matrix with ones or zeros
math.eval('zeros(3, 2)'); // Matrix, [[0, 0], [0, 0], [0, 0]], size [3, 2]
math.eval('ones(3)'); // Matrix, [1, 1, 1], size [3]
math.eval('5 * ones(2, 2)'); // Matrix, [[5, 5], [5, 5]], size [2, 2]
// create an identity matrix
math.eval('eye(2)'); // Matrix, [[1, 0], [0, 1]], size [2, 2]
// create a range
math.eval('1:4'); // Matrix, [1, 2, 3, 4], size [4]
math.eval('0:2:10'); // Matrix, [0, 2, 4, 6, 8, 10], size [6]
```
A subset can be retrieved from a matrix using indexes and a subset of a matrix
can be replaced by using indexes. Indexes are enclosed in square brackets, and
contain a number or a range for each of the matrix dimensions. A range can have
its start and/or end undefined. When the start is undefined, the range will start
at 1, when the end is undefined, the range will end at the end of the matrix.
There is a context variable `end` available as well to denote the end of the
matrix.
*IMPORTANT: matrix indexes and ranges work differently from the math.js indexes
in JavaScript: They are one-based with an included upper-bound, similar to most
math applications.*
```js
parser = math.parser();
// create matrices
parser.eval('a = [1, 2; 3, 4]'); // Matrix, [[1, 2], [3, 4]]
parser.eval('b = zeros(2, 2)'); // Matrix, [[0, 0], [0, 0]]
parser.eval('c = 5:9'); // Matrix, [5, 6, 7, 8, 9]
// replace a subset in a matrix
parser.eval('b[1, 1:2] = [5, 6]'); // Matrix, [[5, 6], [0, 0]]
parser.eval('b[2, :] = [7, 8]'); // Matrix, [[5, 6], [7, 8]]
// perform a matrix calculation
parser.eval('d = a * b'); // Matrix, [[19, 22], [43, 50]]
// retrieve a subset of a matrix
parser.eval('d[2, 1]'); // 43
parser.eval('d[2, 1:end]'); // Matrix, [[43, 50]]
parser.eval('c[end - 1 : -1 : 2]'); // Matrix, [8, 7, 6]
```
## Objects
Objects in math.js work the same as in languages like JavaScript and Python.
An object is enclosed by square brackets `{`, `}`, and contains a set of
comma separated key/value pairs. Keys and values are separated by a colon `:`.
Keys can be a symbol like `prop` or a string like `"prop"`.
```js
math.eval('{a: 2 + 1, b: 4}'); // {a: 3, b: 4}
math.eval('{"a": 2 + 1, "b": 4}'); // {a: 3, b: 4}
```
Objects can contain objects:
```js
math.eval('{a: 2, b: {c: 3, d: 4}}'); // {a: 2, b: {c: 3, d: 4}}
```
Object properties can be retrieved or replaced using dot notation or bracket
notation. Unlike JavaScript, when setting a property value, the whole object
is returned, not the property value
```js
var scope = {
obj: {
prop: 42
}
};
// retrieve properties
math.eval('obj.prop', scope); // 42
math.eval('obj["prop"]', scope); // 42
// set properties (returns the whole object, not the property value!)
math.eval('obj.prop = 43', scope); // {prop: 43}
math.eval('obj["prop"] = 43', scope); // {prop: 43}
scope.obj; // {prop: 43}
```
## Multi-line expressions
An expression can contain multiple lines, and expressions can be spread over
multiple lines. Lines can be separated by a newline character `\n` or by a
semicolon `;`. Output of statements followed by a semicolon will be hidden from
the output, and empty lines are ignored. The output is returned as a `ResultSet`,
with an entry for every visible statement.
```js
// a multi-line expression
math.eval('1 * 3 \n 2 * 3 \n 3 * 3'); // ResultSet, [3, 6, 9]
// semicolon statements are hidden from the output
math.eval('a=3; b=4; a + b \n a * b'); // ResultSet, [7, 12]
// single expression spread over multiple lines
math.eval('a = 2 +\n 3'); // 5
math.eval('[\n 1, 2;\n 3, 4\n]'); // Matrix, [[1, 2], [3, 4]]
```
The results can be read from a `ResultSet` via the property `ResultSet.entries`
which is an `Array`, or by calling `ResultSet.valueOf()`, which returns the
array with results.
## Implicit multiplication
The expression parser supports implicit multiplication. Implicit multiplication
has the same precedence as explicit multiplications and divisions, so `3/4 mm`
is evaluated as `(3 / 4) * mm`.
Parentheses are parsed as a function call when there is a symbol or accessor on
the left hand side, like `sqrt(4)` or `obj.method(4)`. In other cases the
parentheses are interpreted as an implicit multiplication.
Implicit multiplication can be tricky as there is ambiguity on how an expression
is evaluated. Use it carefully.
Here some examples:
Expression | Evaluated as | Result
--------------- | ----------------- | ------------------
(1 + 3) pi | (1 + 3) * pi | 12.566370614359172
(4 - 1) 2 | (4 - 1) * 2 | 6
3 / 4 mm | (3 / 4) * mm | 0.75 mm
2 + 3 i | 2 + (3 * i) | 2 + 3i
(1 + 2) (4 - 2) | (1 + 2) * (4 - 2) | 6
sqrt(4) (1 + 2) | sqrt(4) * (1 + 2) | 6
## Comments
Comments can be added to explain or describe calculations in the text. A comment
starts with a sharp sign character `#`, and ends at the end of the line. A line
can contain a comment only, or can contain an expression followed by a comment.
```js
var parser = math.parser();
parser.eval('# define some variables');
parser.eval('width = 3'); // 3
parser.eval('height = 4'); // 4
parser.eval('width * height # calculate the area'); // 12
```

View File

@@ -0,0 +1,3 @@
# Extension
This page has been moved [here](core/extension.md).

View File

@@ -0,0 +1,113 @@
# Getting Started
This getting started describes how to install, load, and use math.js.
## Install
Math.js can be installed using various package managers like [npm](https://npmjs.org/) and [bower](http://bower.io/), or by just downloading the library from the website: [http://mathjs.org/download.html](http://mathjs.org/download.html).
To install via npm, run:
npm install mathjs
Other ways to install math.js are described on the [website](http://mathjs.org/download.html).
## Load
Math.js can be used in node.js and in the browser. The library must be loaded
and instantiated. When creating an instance, one can optionally provide
configuration options as described in
[Configuration](configuration.md).
### Node.js
Load math.js in [node.js](http://nodejs.org/):
```js
// load math.js
var math = require('mathjs');
// use math.js
math.sqrt(-4); // 2i
```
### Browser
Math.js can be loaded as a regular JavaScript file in the browser:
```html
<!DOCTYPE HTML>
<html>
<head>
<script src="math.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
// use math.js
math.sqrt(-4); // 2i
</script>
</body>
</html>
```
If support for old browsers (Internet Explorer 8 and older) is required,
the [es5-shim](https://github.com/kriskowal/es5-shim) library must be loaded
as well.
### Require.js
Load math.js in the browser using [require.js](http://requirejs.org/):
```js
require.config({
paths: {
mathjs: 'path/to/mathjs',
}
});
require(['mathjs'], function (math) {
// use math.js
math.sqrt(-4); // 2i
});
```
## Use
Math.js can be used similar to JavaScript's built-in Math library. Besides that,
math.js can evaluate expressions (see [Expressions](expressions/index.md)) and
supports chaining (see [Chaining](chaining.md)).
The example code below shows how to use math.js. More examples can be found in the
section [Examples](http://mathjs.org/examples/index.html).
```js
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chained operations
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Next
To learn more about math.js, check out the available documentation and examples:
- [Documentation](index.md)
- [Examples](http://mathjs.org/examples/index.html)

38
nodered/rootfs/data/node_modules/mathjs/docs/index.md generated vendored Normal file
View File

@@ -0,0 +1,38 @@
# Documentation
[Math.js](http://mathjs.org) is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with different data types like numbers, big numbers, complex numbers, fractions, units, and matrices.
Math.js can be used in the browser, in node.js and in any JavaScript engine. Installation and download instructions are available on the [Download page](http://mathjs.org/download.html) of the website.
## Getting Started
- [Getting Started](getting_started.md)
- [Examples](http://mathjs.org/examples/index.html)
## Documentation
- **[Core](core/index.md)**
- [Configuration](core/configuration.md)
- [Chaining](core/chaining.md)
- [Extension](core/extension.md)
- [Serialization](core/serialization.md)
- **[Expressions](expressions/index.md)**
- [Parsing and evaluation](expressions/parsing.md)
- [Syntax](expressions/syntax.md)
- [Expression trees](expressions/expression_trees.md)
- [Algebra](expressions/algebra.md)
- [Customization](expressions/customization.md)
- **[Data Types](datatypes/index.md)**
- [Numbers](datatypes/numbers.md)
- [BigNumbers](datatypes/bignumbers.md)
- [Fractions](datatypes/fractions.md)
- [Complex Numbers](datatypes/complex_numbers.md)
- [Matrices](datatypes/matrices.md)
- [Units](datatypes/units.md)
- **[Reference](reference/index.md)**
- [Classes](reference/classes.md)
- [Functions](reference/functions.md)
- [Constants](reference/constants.md)
- [Custom bundling](custom_bundling.md)
- [Command Line Interface](command_line_interface.md)
- [History](../HISTORY.md)

View File

@@ -0,0 +1,87 @@
# Class Reference
This page lists all the various class types in Math.js. Every top-level function is listed here and links to its detailed reference to other parts of the documentation.
## math
The "math" namespace contains the entire math.js functionality. All of the mathematical functions are available in the "math" namespace, and allow for inputs of various types.
- [Function reference](functions.md)
- [Constant reference](constants.md)
## Unit
Stores values for a scalar unit and its postfix. (eg `100 mm` or `100 kg`). Although the `Unit` class contains public functions documented as follows, using the following API directly is *not* recommended. Prefer using the functions in the "math" namespace wherever possible.
- [Overview](../datatypes/units.md)
- [Class API](classes/unit.md)
## Fraction
Stores values for a fractional number.
- [Overview](../datatypes/fractions.md)
- [Class API](https://github.com/infusion/Fraction.js/)
## BigNumber
Stores values for a arbitrary-precision floating point number.
- [Overview](../datatypes/bignumbers.md)
- [Class API](http://mikemcl.github.io/decimal.js/)
## Matrix
Two types of matrix classes are available in math.js, for storage of dense and sparse matrices. Although they contain public functions documented as follows, using the following API directly is *not* recommended. Prefer using the functions in the "math" namespace wherever possible.
- [Overview](../datatypes/matrices.md)
- [DenseMatrix](classes/densematrix.md)
- [SparseMatrix](classes/sparsematrix.md)
Classes used internally that may be of use to developers:
- [Index](classes/matrixindex.md)
- [Range](classes/matrixrange.md)
- [ResultSet](classes/matrixrange.md)
- [FibonacciHeap](classes/fibonacciheap.md)
## Complex
Stores values for a complex number.
- [Overview](../datatypes/complex_numbers.md)
- [Class API](https://github.com/infusion/Complex.js/)
## Parser
The Parser object returned by `math.parser()`.
- [Overview](../expressions/parsing.md)
## Node
A node in an expression-tree, which can be used to analyze, manipulate, and evaluate expressions.
- [Overview](../expressions/expression_trees.md)
`Node` is the base class of all other node classes:
- [AccessorNode](../expressions/expression_trees.md#accessornode)
- [ArrayNode](../expressions/expression_trees.md#arraynode)
- [AssignmentNode](../expressions/expression_trees.md#assignmentnode)
- [BlockNode](../expressions/expression_trees.md#blocknode)
- [ConditionalNode](../expressions/expression_trees.md#conditionalnode)
- [ConstantNode](../expressions/expression_trees.md#constantnode)
- [FunctionAssignmentNode](../expressions/expression_trees.md#functionassignmentnode)
- [FunctionNode](../expressions/expression_trees.md#functionnode)
- [IndexNode](../expressions/expression_trees.md#indexnode)
- [ObjectNode](../expressions/expression_trees.md#objectnode)
- [OperatorNode](../expressions/expression_trees.md#operatornode)
- [ParenthesisNode](../expressions/expression_trees.md#parenthesisnode)
- [RangeNode](../expressions/expression_trees.md#rangenode)
- [SymbolNode](../expressions/expression_trees.md#symbolnode)
- [UpdateNode](../expressions/expression_trees.md#updatenode)

View File

@@ -0,0 +1,247 @@
<a name="DenseMatrix"></a>
## DenseMatrix
Dense Matrix implementation. This type implements an efficient Array format
for dense matrices.
* _instance_
* [.storage()](#DenseMatrix+storage) ⇒ <code>string</code>
* [.datatype()](#DenseMatrix+datatype) ⇒ <code>string</code>
* [.create(data, [datatype])](#DenseMatrix+create)
* [.subset(index, [replacement], [defaultValue])](#DenseMatrix+subset)
* [.get(index)](#DenseMatrix+get) ⇒ <code>\*</code>
* [.set(index, value, [defaultValue])](#DenseMatrix+set) ⇒ <code>DenseMatrix</code>
* [.resize(size, [defaultValue], [copy])](#DenseMatrix+resize) ⇒ <code>Matrix</code>
* [.clone()](#DenseMatrix+clone) ⇒ <code>DenseMatrix</code>
* [.size()](#DenseMatrix+size) ⇒ <code>Array.&lt;number&gt;</code>
* [.map(callback)](#DenseMatrix+map) ⇒ <code>DenseMatrix</code>
* [.forEach(callback)](#DenseMatrix+forEach)
* [.toArray()](#DenseMatrix+toArray) ⇒ <code>Array</code>
* [.valueOf()](#DenseMatrix+valueOf) ⇒ <code>Array</code>
* [.format([options])](#DenseMatrix+format) ⇒ <code>string</code>
* [.toString()](#DenseMatrix+toString) ⇒ <code>string</code>
* [.toJSON()](#DenseMatrix+toJSON) ⇒ <code>Object</code>
* [.diagonal([k])](#DenseMatrix+diagonal) ⇒ <code>Array</code>
* [.swapRows(i, j)](#DenseMatrix+swapRows) ⇒ <code>Matrix</code>
* _static_
* [.diagonal(size, value, [k], [defaultValue])](#DenseMatrix.diagonal) ⇒ <code>DenseMatrix</code>
* [.fromJSON(json)](#DenseMatrix.fromJSON) ⇒ <code>DenseMatrix</code>
* [.preprocess(data)](#DenseMatrix.preprocess) ⇒ <code>Array</code>
<a name="DenseMatrix+storage"></a>
### denseMatrix.storage() ⇒ <code>string</code>
Get the storage format used by the matrix.
Usage:
```js
var format = matrix.storage() // retrieve storage format
```
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>string</code> - The storage format.
<a name="DenseMatrix+datatype"></a>
### denseMatrix.datatype() ⇒ <code>string</code>
Get the datatype of the data stored in the matrix.
Usage:
```js
var format = matrix.datatype() // retrieve matrix datatype
```
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>string</code> - The datatype.
<a name="DenseMatrix+create"></a>
### denseMatrix.create(data, [datatype])
Create a new DenseMatrix
**Kind**: instance method of <code>DenseMatrix</code>
| Param | Type |
| --- | --- |
| data | <code>Array</code> |
| [datatype] | <code>string</code> |
<a name="DenseMatrix+subset"></a>
### denseMatrix.subset(index, [replacement], [defaultValue])
Get a subset of the matrix, or replace a subset of the matrix.
Usage:
```js
var subset = matrix.subset(index) // retrieve subset
var value = matrix.subset(index, replacement) // replace subset
```
**Kind**: instance method of <code>DenseMatrix</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| index | <code>Index</code> | | |
| [replacement] | <code>Array</code> &#124; <code>DenseMatrix</code>&#124; <code>\*</code> | | |
| [defaultValue] | <code>\*</code> | <code>0</code> | Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be filled with zeros. |
<a name="DenseMatrix+get"></a>
### denseMatrix.get(index) ⇒ <code>\*</code>
Get a single element from the matrix.
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>\*</code> - value
| Param | Type | Description |
| --- | --- | --- |
| index | <code>Array.&lt;number&gt;</code> | Zero-based index |
<a name="DenseMatrix+set"></a>
### denseMatrix.set(index, value, [defaultValue]) ⇒ <code>DenseMatrix</code>
Replace a single element in the matrix.
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>DenseMatrix</code>- self
| Param | Type | Description |
| --- | --- | --- |
| index | <code>Array.&lt;number&gt;</code> | Zero-based index |
| value | <code>\*</code> | |
| [defaultValue] | <code>\*</code> | Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be left undefined. |
<a name="DenseMatrix+resize"></a>
### denseMatrix.resize(size, [defaultValue], [copy]) ⇒ <code>Matrix</code>
Resize the matrix to the given size. Returns a copy of the matrix when
`copy=true`, otherwise return the matrix itself (resize in place).
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>Matrix</code> - The resized matrix
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| size | <code>Array.&lt;number&gt;</code> | | The new size the matrix should have. |
| [defaultValue] | <code>\*</code> | <code>0</code> | Default value, filled in on new entries. If not provided, the matrix elements will be filled with zeros. |
| [copy] | <code>boolean</code> | | Return a resized copy of the matrix |
<a name="DenseMatrix+clone"></a>
### denseMatrix.clone() ⇒ <code>DenseMatrix</code>
Create a clone of the matrix
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>DenseMatrix</code>- clone
<a name="DenseMatrix+size"></a>
### denseMatrix.size() ⇒ <code>Array.&lt;number&gt;</code>
Retrieve the size of the matrix.
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>Array.&lt;number&gt;</code> - size
<a name="DenseMatrix+map"></a>
### denseMatrix.map(callback) ⇒ <code>DenseMatrix</code>
Create a new matrix with the results of the callback function executed on
each entry of the matrix.
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>DenseMatrix</code>- matrix
| Param | Type | Description |
| --- | --- | --- |
| callback | <code>function</code> | The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed. |
<a name="DenseMatrix+forEach"></a>
### denseMatrix.forEach(callback)
Execute a callback function on each entry of the matrix.
**Kind**: instance method of <code>DenseMatrix</code>
| Param | Type | Description |
| --- | --- | --- |
| callback | <code>function</code> | The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed. |
<a name="DenseMatrix+toArray"></a>
### denseMatrix.toArray() ⇒ <code>Array</code>
Create an Array with a copy of the data of the DenseMatrix
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>Array</code> - array
<a name="DenseMatrix+valueOf"></a>
### denseMatrix.valueOf() ⇒ <code>Array</code>
Get the primitive value of the DenseMatrix: a multidimensional array
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>Array</code> - array
<a name="DenseMatrix+format"></a>
### denseMatrix.format([options]) ⇒ <code>string</code>
Get a string representation of the matrix, with optional formatting options.
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>string</code> - str
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> &#124; <code>number</code> &#124; <code>function</code> | Formatting options. See lib/utils/number:format for a description of the available options. |
<a name="DenseMatrix+toString"></a>
### denseMatrix.toString() ⇒ <code>string</code>
Get a string representation of the matrix
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>string</code> - str
<a name="DenseMatrix+toJSON"></a>
### denseMatrix.toJSON() ⇒ <code>Object</code>
Get a JSON representation of the matrix
**Kind**: instance method of <code>DenseMatrix</code>
<a name="DenseMatrix+diagonal"></a>
### denseMatrix.diagonal([k]) ⇒ <code>Array</code>
Get the kth Matrix diagonal.
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>Array</code> - The array vector with the diagonal values.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [k] | <code>number</code> &#124; <code>BigNumber</code> | <code>0</code> | The kth diagonal where the vector will retrieved. |
<a name="DenseMatrix+swapRows"></a>
### denseMatrix.swapRows(i, j) ⇒ <code>Matrix</code>
Swap rows i and j in Matrix.
**Kind**: instance method of <code>DenseMatrix</code>
**Returns**: <code>Matrix</code> - The matrix reference
| Param | Type | Description |
| --- | --- | --- |
| i | <code>number</code> | Matrix row index 1 |
| j | <code>number</code> | Matrix row index 2 |
<a name="DenseMatrix.diagonal"></a>
### DenseMatrix.diagonal(size, value, [k], [defaultValue]) ⇒ <code>DenseMatrix</code>
Create a diagonal matrix.
**Kind**: static method of <code>DenseMatrix</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| size | <code>Array</code> | | The matrix size. |
| value | <code>number</code> &#124; <code>Array</code> | | The values for the diagonal. |
| [k] | <code>number</code> &#124; <code>BigNumber</code> | <code>0</code> | The kth diagonal where the vector will be filled in. |
| [defaultValue] | <code>number</code> | | The default value for non-diagonal |
<a name="DenseMatrix.fromJSON"></a>
### DenseMatrix.fromJSON(json) ⇒ <code>DenseMatrix</code>
Generate a matrix from a JSON object
**Kind**: static method of <code>DenseMatrix</code>
| Param | Type | Description |
| --- | --- | --- |
| json | <code>Object</code> | An object structured like `{"mathjs": "DenseMatrix", data: [], size: []}`, where mathjs is optional |
<a name="DenseMatrix.preprocess"></a>
### DenseMatrix.preprocess(data) ⇒ <code>Array</code>
Preprocess data, which can be an Array or DenseMatrix with nested Arrays and
Matrices. Replaces all nested Matrices with Arrays
**Kind**: static method of <code>DenseMatrix</code>
**Returns**: <code>Array</code> - data
| Param | Type |
| --- | --- |
| data | <code>Array</code> |

View File

@@ -0,0 +1,70 @@
<a name="FibonacciHeap"></a>
## FibonacciHeap
* [new FibonacciHeap()](#new_FibonacciHeap_new)
* _instance_
* [.insert()](#FibonacciHeap+insert)
* [.size()](#FibonacciHeap+size)
* [.clear()](#FibonacciHeap+clear)
* [.isEmpty()](#FibonacciHeap+isEmpty)
* [.extractMinimum()](#FibonacciHeap+extractMinimum)
* [.remove()](#FibonacciHeap+remove)
* _static_
* [._decreaseKey()](#FibonacciHeap._decreaseKey)
* [._cut()](#FibonacciHeap._cut)
* [._cascadingCut()](#FibonacciHeap._cascadingCut)
* [._linkNodes()](#FibonacciHeap._linkNodes)
<a name="new_FibonacciHeap_new"></a>
### new FibonacciHeap()
Creates a new instance of a Fibonacci Heap.
<a name="FibonacciHeap+insert"></a>
### fibonacciHeap.insert()
Inserts a new data element into the heap. No heap consolidation is
performed at this time, the new node is simply inserted into the root
list of this heap. Running time: O(1) actual.
**Kind**: instance method of <code>[FibonacciHeap](#FibonacciHeap)</code>
<a name="FibonacciHeap+size"></a>
### fibonacciHeap.size()
Returns the number of nodes in heap. Running time: O(1) actual.
**Kind**: instance method of <code>[FibonacciHeap](#FibonacciHeap)</code>
<a name="FibonacciHeap+clear"></a>
### fibonacciHeap.clear()
Removes all elements from this heap.
**Kind**: instance method of <code>[FibonacciHeap](#FibonacciHeap)</code>
<a name="FibonacciHeap+isEmpty"></a>
### fibonacciHeap.isEmpty()
Returns true if the heap is empty, otherwise false.
**Kind**: instance method of <code>[FibonacciHeap](#FibonacciHeap)</code>
<a name="FibonacciHeap+extractMinimum"></a>
### fibonacciHeap.extractMinimum()
Extracts the node with minimum key from heap. Amortized running
time: O(log n).
**Kind**: instance method of <code>[FibonacciHeap](#FibonacciHeap)</code>
<a name="FibonacciHeap+remove"></a>
### fibonacciHeap.remove()
Removes a node from the heap given the reference to the node. The trees
in the heap will be consolidated, if necessary. This operation may fail
to remove the correct element if there are nodes with key value -Infinity.
Running time: O(log n) amortized.
**Kind**: instance method of <code>[FibonacciHeap](#FibonacciHeap)</code>
<a name="FibonacciHeap._decreaseKey"></a>
### FibonacciHeap._decreaseKey()
Decreases the key value for a heap node, given the new value to take on.
The structure of the heap may be changed and will not be consolidated.
Running time: O(1) amortized.
**Kind**: static method of <code>[FibonacciHeap](#FibonacciHeap)</code>
<a name="FibonacciHeap._cut"></a>
### FibonacciHeap._cut()
The reverse of the link operation: removes node from the child list of parent.
This method assumes that min is non-null. Running time: O(1).
**Kind**: static method of <code>[FibonacciHeap](#FibonacciHeap)</code>
<a name="FibonacciHeap._cascadingCut"></a>

View File

@@ -0,0 +1,133 @@
<a name="Index"></a>
## Index
* [new Index(...ranges)](#new_Index_new)
* _instance_
* [.valueOf](#Index+valueOf) ⇒ <code>Array</code>
* [.clone()](#Index+clone) ⇒ <code>[Index](#Index)</code>
* [.size()](#Index+size) ⇒ <code>Array.&lt;number&gt;</code>
* [.max()](#Index+max) ⇒ <code>Array.&lt;number&gt;</code>
* [.min()](#Index+min) ⇒ <code>Array.&lt;number&gt;</code>
* [.forEach(callback)](#Index+forEach)
* [.dimension(dim)](#Index+dimension) ⇒ <code>Range</code> &#124; <code>null</code>
* [.isScalar()](#Index+isScalar) ⇒ <code>boolean</code>
* [.toArray()](#Index+toArray) ⇒ <code>Array</code>
* [.toString()](#Index+toString) ⇒ <code>String</code>
* [.toJSON()](#Index+toJSON) ⇒ <code>Object</code>
* _static_
* [.fromJSON(json)](#Index.fromJSON) ⇒ <code>[Index](#Index)</code>
<a name="new_Index_new"></a>
### new Index(...ranges)
Create an index. An Index can store ranges and sets for multiple dimensions.
Matrix.get, Matrix.set, and math.subset accept an Index as input.
Usage:
```js
var index = new Index(range1, range2, matrix1, array1, ...);
```
Where each parameter can be any of:
- A number
- An instance of Range
- An Array with the Set values
- A Matrix with the Set values
The parameters start, end, and step must be integer numbers.
| Param | Type |
| --- | --- |
| ...ranges | <code>\*</code> |
<a name="Index+valueOf"></a>
### index.valueOf ⇒ <code>Array</code>
Get the primitive value of the Index, a two dimensional array.
Equivalent to Index.toArray().
**Kind**: instance property of <code>[Index](#Index)</code>
**Returns**: <code>Array</code> - array
<a name="Index+clone"></a>
### index.clone() ⇒ <code>[Index](#Index)</code>
Create a clone of the index
**Kind**: instance method of <code>[Index](#Index)</code>
**Returns**: <code>[Index](#Index)</code> - clone
<a name="Index+size"></a>
### index.size() ⇒ <code>Array.&lt;number&gt;</code>
Retrieve the size of the index, the number of elements for each dimension.
**Kind**: instance method of <code>[Index](#Index)</code>
**Returns**: <code>Array.&lt;number&gt;</code> - size
<a name="Index+max"></a>
### index.max() ⇒ <code>Array.&lt;number&gt;</code>
Get the maximum value for each of the indexes ranges.
**Kind**: instance method of <code>[Index](#Index)</code>
**Returns**: <code>Array.&lt;number&gt;</code> - max
<a name="Index+min"></a>
### index.min() ⇒ <code>Array.&lt;number&gt;</code>
Get the minimum value for each of the indexes ranges.
**Kind**: instance method of <code>[Index](#Index)</code>
**Returns**: <code>Array.&lt;number&gt;</code> - min
<a name="Index+forEach"></a>
### index.forEach(callback)
Loop over each of the ranges of the index
**Kind**: instance method of <code>[Index](#Index)</code>
| Param | Type | Description |
| --- | --- | --- |
| callback | <code>function</code> | Called for each range with a Range as first argument, the dimension as second, and the index object as third. |
<a name="Index+dimension"></a>
### index.dimension(dim) ⇒ <code>Range</code> &#124; <code>null</code>
Retrieve the dimension for the given index
**Kind**: instance method of <code>[Index](#Index)</code>
**Returns**: <code>Range</code> &#124; <code>null</code> - range
| Param | Type | Description |
| --- | --- | --- |
| dim | <code>Number</code> | Number of the dimension |
<a name="Index+isScalar"></a>
### index.isScalar() ⇒ <code>boolean</code>
Test whether this index contains only a single value.
This is the case when the index is created with only scalar values as ranges,
not for ranges resolving into a single value.
**Kind**: instance method of <code>[Index](#Index)</code>
**Returns**: <code>boolean</code> - isScalar
<a name="Index+toArray"></a>
### index.toArray() ⇒ <code>Array</code>
Expand the Index into an array.
For example new Index([0,3], [2,7]) returns [[0,1,2], [2,3,4,5,6]]
**Kind**: instance method of <code>[Index](#Index)</code>
**Returns**: <code>Array</code> - array
<a name="Index+toString"></a>
### index.toString() ⇒ <code>String</code>
Get the string representation of the index, for example '[2:6]' or '[0:2:10, 4:7, [1,2,3]]'
**Kind**: instance method of <code>[Index](#Index)</code>
**Returns**: <code>String</code> - str
<a name="Index+toJSON"></a>
### index.toJSON() ⇒ <code>Object</code>
Get a JSON representation of the Index
**Kind**: instance method of <code>[Index](#Index)</code>
**Returns**: <code>Object</code> - Returns a JSON object structured as:
`{"mathjs": "Index", "ranges": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}`
<a name="Index.fromJSON"></a>
### Index.fromJSON(json) ⇒ <code>[Index](#Index)</code>
Instantiate an Index from a JSON object
**Kind**: static method of <code>[Index](#Index)</code>
| Param | Type | Description |
| --- | --- | --- |
| json | <code>Object</code> | A JSON object structured as: `{"mathjs": "Index", "dimensions": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}` |

View File

@@ -0,0 +1,158 @@
<a name="Range"></a>
## Range
* [new Range(start, end, [step])](#new_Range_new)
* _instance_
* [.size()](#Range+size) ⇒ <code>Array.&lt;number&gt;</code>
* [.min()](#Range+min) ⇒ <code>number</code> &#124; <code>undefined</code>
* [.max()](#Range+max) ⇒ <code>number</code> &#124; <code>undefined</code>
* [.forEach(callback)](#Range+forEach)
* [.map(callback)](#Range+map) ⇒ <code>Array</code>
* [.toArray()](#Range+toArray) ⇒ <code>Array</code>
* [.valueOf()](#Range+valueOf) ⇒ <code>Array</code>
* [.format([options])](#Range+format) ⇒ <code>string</code>
* [.toString()](#Range+toString) ⇒ <code>string</code>
* [.toJSON()](#Range+toJSON) ⇒ <code>Object</code>
* _static_
* [.parse(str)](#Range.parse) ⇒ <code>[Range](#Range)</code> &#124; <code>null</code>
* [.fromJSON(json)](#Range.fromJSON) ⇒ <code>[Range](#Range)</code>
<a name="new_Range_new"></a>
### new Range(start, end, [step])
Create a range. A range has a start, step, and end, and contains functions
to iterate over the range.
A range can be constructed as:
```js
var range = new Range(start, end);
var range = new Range(start, end, step);
```
To get the result of the range:
```js
range.forEach(function (x) {
console.log(x);
});
range.map(function (x) {
return math.sin(x);
});
range.toArray();
```
Example usage:
```js
var c = new Range(2, 6); // 2:1:5
c.toArray(); // [2, 3, 4, 5]
var d = new Range(2, -3, -1); // 2:-1:-2
d.toArray(); // [2, 1, 0, -1, -2]
```
| Param | Type | Description |
| --- | --- | --- |
| start | <code>number</code> | included lower bound |
| end | <code>number</code> | excluded upper bound |
| [step] | <code>number</code> | step size, default value is 1 |
<a name="Range+size"></a>
### range.size() ⇒ <code>Array.&lt;number&gt;</code>
Retrieve the size of the range.
Returns an array containing one number, the number of elements in the range.
**Kind**: instance method of <code>[Range](#Range)</code>
**Returns**: <code>Array.&lt;number&gt;</code> - size
<a name="Range+min"></a>
### range.min() ⇒ <code>number</code> &#124; <code>undefined</code>
Calculate the minimum value in the range
**Kind**: instance method of <code>[Range](#Range)</code>
**Returns**: <code>number</code> &#124; <code>undefined</code> - min
<a name="Range+max"></a>
### range.max() ⇒ <code>number</code> &#124; <code>undefined</code>
Calculate the maximum value in the range
**Kind**: instance method of <code>[Range](#Range)</code>
**Returns**: <code>number</code> &#124; <code>undefined</code> - max
<a name="Range+forEach"></a>
### range.forEach(callback)
Execute a callback function for each value in the range.
**Kind**: instance method of <code>[Range](#Range)</code>
| Param | Type | Description |
| --- | --- | --- |
| callback | <code>function</code> | The callback method is invoked with three parameters: the value of the element, the index of the element, and the Range being traversed. |
<a name="Range+map"></a>
### range.map(callback) ⇒ <code>Array</code>
Execute a callback function for each value in the Range, and return the
results as an array
**Kind**: instance method of <code>[Range](#Range)</code>
**Returns**: <code>Array</code> - array
| Param | Type | Description |
| --- | --- | --- |
| callback | <code>function</code> | The callback method is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed. |
<a name="Range+toArray"></a>
### range.toArray() ⇒ <code>Array</code>
Create an Array with a copy of the Ranges data
**Kind**: instance method of <code>[Range](#Range)</code>
**Returns**: <code>Array</code> - array
<a name="Range+valueOf"></a>
### range.valueOf() ⇒ <code>Array</code>
Get the primitive value of the Range, a one dimensional array
**Kind**: instance method of <code>[Range](#Range)</code>
**Returns**: <code>Array</code> - array
<a name="Range+format"></a>
### range.format([options]) ⇒ <code>string</code>
Get a string representation of the range, with optional formatting options.
Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11'
**Kind**: instance method of <code>[Range](#Range)</code>
**Returns**: <code>string</code> - str
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> &#124; <code>number</code> &#124; <code>function</code> | Formatting options. See lib/utils/number:format for a description of the available options. |
<a name="Range+toString"></a>
### range.toString() ⇒ <code>string</code>
Get a string representation of the range.
**Kind**: instance method of <code>[Range](#Range)</code>
<a name="Range+toJSON"></a>
### range.toJSON() ⇒ <code>Object</code>
Get a JSON representation of the range
**Kind**: instance method of <code>[Range](#Range)</code>
**Returns**: <code>Object</code> - Returns a JSON object structured as:
`{"mathjs": "Range", "start": 2, "end": 4, "step": 1}`
<a name="Range.parse"></a>
### Range.parse(str) ⇒ <code>[Range](#Range)</code> &#124; <code>null</code>
Parse a string into a range,
The string contains the start, optional step, and end, separated by a colon.
If the string does not contain a valid range, null is returned.
For example str='0:2:11'.
**Kind**: static method of <code>[Range](#Range)</code>
**Returns**: <code>[Range](#Range)</code> &#124; <code>null</code> - range
| Param | Type |
| --- | --- |
| str | <code>string</code> |
<a name="Range.fromJSON"></a>
### Range.fromJSON(json) ⇒ <code>[Range](#Range)</code>
Instantiate a Range from a JSON object
**Kind**: static method of <code>[Range](#Range)</code>
| Param | Type | Description |
| --- | --- | --- |
| json | <code>Object</code> | A JSON object structured as: `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` |

View File

@@ -0,0 +1,47 @@
<a name="ResultSet"></a>
## ResultSet
* [new ResultSet(entries)](#new_ResultSet_new)
* _instance_
* [.valueOf()](#ResultSet+valueOf) ⇒ <code>Array</code>
* [.toString()](#ResultSet+toString) ⇒ <code>string</code>
* [.toJSON()](#ResultSet+toJSON) ⇒ <code>Object</code>
* _static_
* [.fromJSON(json)](#ResultSet.fromJSON) ⇒ <code>[ResultSet](#ResultSet)</code>
<a name="new_ResultSet_new"></a>
### new ResultSet(entries)
A ResultSet contains a list or results
| Param | Type |
| --- | --- |
| entries | <code>Array</code> |
<a name="ResultSet+valueOf"></a>
### resultSet.valueOf() ⇒ <code>Array</code>
Returns the array with results hold by this ResultSet
**Kind**: instance method of <code>[ResultSet](#ResultSet)</code>
**Returns**: <code>Array</code> - entries
<a name="ResultSet+toString"></a>
### resultSet.toString() ⇒ <code>string</code>
Returns the stringified results of the ResultSet
**Kind**: instance method of <code>[ResultSet](#ResultSet)</code>
**Returns**: <code>string</code> - string
<a name="ResultSet+toJSON"></a>
### resultSet.toJSON() ⇒ <code>Object</code>
Get a JSON representation of the ResultSet
**Kind**: instance method of <code>[ResultSet](#ResultSet)</code>
**Returns**: <code>Object</code> - Returns a JSON object structured as:
`{"mathjs": "ResultSet", "entries": [...]}`
<a name="ResultSet.fromJSON"></a>
### ResultSet.fromJSON(json) ⇒ <code>[ResultSet](#ResultSet)</code>
Instantiate a ResultSet from a JSON object
**Kind**: static method of <code>[ResultSet](#ResultSet)</code>
| Param | Type | Description |
| --- | --- | --- |
| json | <code>Object</code> | A JSON object structured as: `{"mathjs": "ResultSet", "entries": [...]}` |

View File

@@ -0,0 +1,245 @@
<a name="SparseMatrix"></a>
## SparseMatrix
Sparse Matrix implementation. This type implements a Compressed Column Storage format
for sparse matrices.
* _instance_
* [.storage()](#SparseMatrix+storage) ⇒ <code>string</code>
* [.datatype()](#SparseMatrix+datatype) ⇒ <code>string</code>
* [.create(data, [datatype])](#SparseMatrix+create)
* [.density()](#SparseMatrix+density) ⇒ <code>number</code>
* [.subset(index, [replacement], [defaultValue])](#SparseMatrix+subset)
* [.get(index)](#SparseMatrix+get) ⇒ <code>\*</code>
* [.set(index, value, [defaultValue])](#SparseMatrix+set) ⇒ <code>[SparseMatrix](#SparseMatrix)</code>
* [.resize(size, [defaultValue], [copy])](#SparseMatrix+resize) ⇒ <code>Matrix</code>
* [.clone()](#SparseMatrix+clone) ⇒ <code>[SparseMatrix](#SparseMatrix)</code>
* [.size()](#SparseMatrix+size) ⇒ <code>Array.&lt;number&gt;</code>
* [.map(callback, [skipZeros])](#SparseMatrix+map) ⇒ <code>[SparseMatrix](#SparseMatrix)</code>
* [.forEach(callback, [skipZeros])](#SparseMatrix+forEach)
* [.toArray()](#SparseMatrix+toArray) ⇒ <code>Array</code>
* [.valueOf()](#SparseMatrix+valueOf) ⇒ <code>Array</code>
* [.format([options])](#SparseMatrix+format) ⇒ <code>string</code>
* [.toString()](#SparseMatrix+toString) ⇒ <code>string</code>
* [.toJSON()](#SparseMatrix+toJSON) ⇒ <code>Object</code>
* [.diagonal([k])](#SparseMatrix+diagonal) ⇒ <code>Matrix</code>
* [.swapRows(i, j)](#SparseMatrix+swapRows) ⇒ <code>Matrix</code>
* _static_
* [.fromJSON(json)](#SparseMatrix.fromJSON) ⇒ <code>[SparseMatrix](#SparseMatrix)</code>
* [.diagonal(size, value, [k], [datatype])](#SparseMatrix.diagonal) ⇒ <code>[SparseMatrix](#SparseMatrix)</code>
<a name="SparseMatrix+storage"></a>
### sparseMatrix.storage() ⇒ <code>string</code>
Get the storage format used by the matrix.
Usage:
```js
var format = matrix.storage() // retrieve storage format
```
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>string</code> - The storage format.
<a name="SparseMatrix+datatype"></a>
### sparseMatrix.datatype() ⇒ <code>string</code>
Get the datatype of the data stored in the matrix.
Usage:
```js
var format = matrix.datatype() // retrieve matrix datatype
```
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>string</code> - The datatype.
<a name="SparseMatrix+create"></a>
### sparseMatrix.create(data, [datatype])
Create a new SparseMatrix
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
| Param | Type |
| --- | --- |
| data | <code>Array</code> |
| [datatype] | <code>string</code> |
<a name="SparseMatrix+density"></a>
### sparseMatrix.density() ⇒ <code>number</code>
Get the matrix density.
Usage:
```js
var density = matrix.density() // retrieve matrix density
```
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>number</code> - The matrix density.
<a name="SparseMatrix+subset"></a>
### sparseMatrix.subset(index, [replacement], [defaultValue])
Get a subset of the matrix, or replace a subset of the matrix.
Usage:
```js
var subset = matrix.subset(index) // retrieve subset
var value = matrix.subset(index, replacement) // replace subset
```
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| index | <code>Index</code> | | |
| [replacement] | <code>Array</code> &#124; <code>Maytrix</code> &#124; <code>\*</code> | | |
| [defaultValue] | <code>\*</code> | <code>0</code> | Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be filled with zeros. |
<a name="SparseMatrix+get"></a>
### sparseMatrix.get(index) ⇒ <code>\*</code>
Get a single element from the matrix.
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>\*</code> - value
| Param | Type | Description |
| --- | --- | --- |
| index | <code>Array.&lt;number&gt;</code> | Zero-based index |
<a name="SparseMatrix+set"></a>
### sparseMatrix.set(index, value, [defaultValue]) ⇒ <code>[SparseMatrix](#SparseMatrix)</code>
Replace a single element in the matrix.
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>[SparseMatrix](#SparseMatrix)</code> - self
| Param | Type | Description |
| --- | --- | --- |
| index | <code>Array.&lt;number&gt;</code> | Zero-based index |
| value | <code>\*</code> | |
| [defaultValue] | <code>\*</code> | Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be set to zero. |
<a name="SparseMatrix+resize"></a>
### sparseMatrix.resize(size, [defaultValue], [copy]) ⇒ <code>Matrix</code>
Resize the matrix to the given size. Returns a copy of the matrix when
`copy=true`, otherwise return the matrix itself (resize in place).
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>Matrix</code> - The resized matrix
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| size | <code>Array.&lt;number&gt;</code> | | The new size the matrix should have. |
| [defaultValue] | <code>\*</code> | <code>0</code> | Default value, filled in on new entries. If not provided, the matrix elements will be filled with zeros. |
| [copy] | <code>boolean</code> | | Return a resized copy of the matrix |
<a name="SparseMatrix+clone"></a>
### sparseMatrix.clone() ⇒ <code>[SparseMatrix](#SparseMatrix)</code>
Create a clone of the matrix
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>[SparseMatrix](#SparseMatrix)</code> - clone
<a name="SparseMatrix+size"></a>
### sparseMatrix.size() ⇒ <code>Array.&lt;number&gt;</code>
Retrieve the size of the matrix.
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>Array.&lt;number&gt;</code> - size
<a name="SparseMatrix+map"></a>
### sparseMatrix.map(callback, [skipZeros]) ⇒ <code>[SparseMatrix](#SparseMatrix)</code>
Create a new matrix with the results of the callback function executed on
each entry of the matrix.
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>[SparseMatrix](#SparseMatrix)</code> - matrix
| Param | Type | Description |
| --- | --- | --- |
| callback | <code>function</code> | The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed. |
| [skipZeros] | <code>boolean</code> | Invoke callback function for non-zero values only. |
<a name="SparseMatrix+forEach"></a>
### sparseMatrix.forEach(callback, [skipZeros])
Execute a callback function on each entry of the matrix.
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
| Param | Type | Description |
| --- | --- | --- |
| callback | <code>function</code> | The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed. |
| [skipZeros] | <code>boolean</code> | Invoke callback function for non-zero values only. |
<a name="SparseMatrix+toArray"></a>
### sparseMatrix.toArray() ⇒ <code>Array</code>
Create an Array with a copy of the data of the SparseMatrix
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>Array</code> - array
<a name="SparseMatrix+valueOf"></a>
### sparseMatrix.valueOf() ⇒ <code>Array</code>
Get the primitive value of the SparseMatrix: a two dimensions array
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>Array</code> - array
<a name="SparseMatrix+format"></a>
### sparseMatrix.format([options]) ⇒ <code>string</code>
Get a string representation of the matrix, with optional formatting options.
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>string</code> - str
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> &#124; <code>number</code> &#124; <code>function</code> | Formatting options. See lib/utils/number:format for a description of the available options. |
<a name="SparseMatrix+toString"></a>
### sparseMatrix.toString() ⇒ <code>string</code>
Get a string representation of the matrix
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>string</code> - str
<a name="SparseMatrix+toJSON"></a>
### sparseMatrix.toJSON() ⇒ <code>Object</code>
Get a JSON representation of the matrix
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
<a name="SparseMatrix+diagonal"></a>
### sparseMatrix.diagonal([k]) ⇒ <code>Matrix</code>
Get the kth Matrix diagonal.
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>Matrix</code> - The matrix vector with the diagonal values.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [k] | <code>number</code> &#124; <code>BigNumber</code> | <code>0</code> | The kth diagonal where the vector will retrieved. |
<a name="SparseMatrix+swapRows"></a>
### sparseMatrix.swapRows(i, j) ⇒ <code>Matrix</code>
Swap rows i and j in Matrix.
**Kind**: instance method of <code>[SparseMatrix](#SparseMatrix)</code>
**Returns**: <code>Matrix</code> - The matrix reference
| Param | Type | Description |
| --- | --- | --- |
| i | <code>number</code> | Matrix row index 1 |
| j | <code>number</code> | Matrix row index 2 |
<a name="SparseMatrix.fromJSON"></a>
### SparseMatrix.fromJSON(json) ⇒ <code>[SparseMatrix](#SparseMatrix)</code>
Generate a matrix from a JSON object
**Kind**: static method of <code>[SparseMatrix](#SparseMatrix)</code>
| Param | Type | Description |
| --- | --- | --- |
| json | <code>Object</code> | An object structured like `{"mathjs": "SparseMatrix", "values": [], "index": [], "ptr": [], "size": []}`, where mathjs is optional |
<a name="SparseMatrix.diagonal"></a>
### SparseMatrix.diagonal(size, value, [k], [datatype]) ⇒ <code>[SparseMatrix](#SparseMatrix)</code>
Create a diagonal matrix.
**Kind**: static method of <code>[SparseMatrix](#SparseMatrix)</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| size | <code>Array</code> | | The matrix size. |
| value | <code>number</code> &#124; <code>Array</code> &#124; <code>Matrix</code> | | The values for the diagonal. |
| [k] | <code>number</code> &#124; <code>BigNumber</code> | <code>0</code> | The kth diagonal where the vector will be filled in. |
| [datatype] | <code>string</code> | | The Matrix datatype, values must be of this datatype. |

View File

@@ -0,0 +1,242 @@
<a name="Unit"></a>
## Unit
* [new Unit([value], [name])](#new_Unit_new)
* _instance_
* [.valueOf](#Unit+valueOf) ⇒ <code>string</code>
* [.clone()](#Unit+clone) ⇒ <code>Unit</code>
* [._isDerived()](#Unit+_isDerived) ⇒ <code>boolean</code>
* [.hasBase(base)](#Unit+hasBase)
* [.equalBase(other)](#Unit+equalBase) ⇒ <code>boolean</code>
* [.equals(other)](#Unit+equals) ⇒ <code>boolean</code>
* [.multiply(other)](#Unit+multiply) ⇒ <code>Unit</code>
* [.divide(other)](#Unit+divide) ⇒ <code>Unit</code>
* [.pow(p)](#Unit+pow) ⇒ <code>Unit</code>
* [.abs(x)](#Unit+abs) ⇒ <code>Unit</code>
* [.to(valuelessUnit)](#Unit+to) ⇒ <code>Unit</code>
* [.toNumber(valuelessUnit)](#Unit+toNumber) ⇒ <code>number</code>
* [.toNumeric(valuelessUnit)](#Unit+toNumeric) ⇒ <code>number</code> &#124; <code>BigNumber</code> &#124; <code>Fraction</code>
* [.toString()](#Unit+toString) ⇒ <code>string</code>
* [.toJSON()](#Unit+toJSON) ⇒ <code>Object</code>
* [.formatUnits()](#Unit+formatUnits) ⇒ <code>string</code>
* [.format([options])](#Unit+format) ⇒ <code>string</code>
* _static_
* [.parse(str)](#Unit.parse) ⇒ <code>Unit</code>
* [.isValuelessUnit(name)](#Unit.isValuelessUnit) ⇒ <code>boolean</code>
* [.fromJSON(json)](#Unit.fromJSON) ⇒ <code>Unit</code>
<a name="new_Unit_new"></a>
### new Unit([value], [name])
A unit can be constructed in the following ways:
```js
var a = new Unit(value, name);
var b = new Unit(null, name);
var c = Unit.parse(str);
```
Example usage:
```js
var a = new Unit(5, 'cm'); // 50 mm
var b = Unit.parse('23 kg'); // 23 kg
var c = math.in(a, new Unit(null, 'm'); // 0.05 m
var d = new Unit(9.81, "m/s^2"); // 9.81 m/s^2
```
| Param | Type | Description |
| --- | --- | --- |
| [value] | <code>number</code> &#124; <code>BigNumber</code> &#124; <code>Fraction</code> &#124; <code>Complex</code> &#124; <code>boolean</code> | A value like 5.2 |
| [name] | <code>string</code> | A unit name like "cm" or "inch", or a derived unit of the form: "u1[^ex1] [u2[^ex2] ...] [/ u3[^ex3] [u4[^ex4]]]", such as "kg m^2/s^2", where each unit appearing after the forward slash is taken to be in the denominator. "kg m^2 s^-2" is a synonym and is also acceptable. Any of the units can include a prefix. |
<a name="Unit+valueOf"></a>
### unit.valueOf ⇒ <code>string</code>
Returns the string representation of the unit.
**Kind**: instance property of <code>Unit</code>
<a name="Unit+clone"></a>
### unit.clone() ⇒ <code>Unit</code>
create a copy of this unit
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>Unit</code> - Returns a cloned version of the unit
<a name="Unit+_isDerived"></a>
### unit._isDerived() ⇒ <code>boolean</code>
Return whether the unit is derived (such as m/s, or cm^2, but not N)
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>boolean</code> - True if the unit is derived
<a name="Unit+hasBase"></a>
### unit.hasBase(base)
check if this unit has given base unit
If this unit is a derived unit, this will ALWAYS return false, since by definition base units are not derived.
**Kind**: instance method of <code>Unit</code>
| Param | Type |
| --- | --- |
| base | <code>BASE_UNITS</code> &#124; <code>STRING</code> &#124; <code>undefined</code> |
<a name="Unit+equalBase"></a>
### unit.equalBase(other) ⇒ <code>boolean</code>
Check if this unit has a base or bases equal to another base or bases
For derived units, the exponent on each base also must match
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>boolean</code> - true if equal base
| Param | Type |
| --- | --- |
| other | <code>Unit</code> |
<a name="Unit+equals"></a>
### unit.equals(other) ⇒ <code>boolean</code>
Check if this unit equals another unit
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>boolean</code> - true if both units are equal
| Param | Type |
| --- | --- |
| other | <code>Unit</code> |
<a name="Unit+multiply"></a>
### unit.multiply(other) ⇒ <code>Unit</code>
Multiply this unit with another one
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>Unit</code> - product of this unit and the other unit
| Param | Type |
| --- | --- |
| other | <code>Unit</code> |
<a name="Unit+divide"></a>
### unit.divide(other) ⇒ <code>Unit</code>
Divide this unit by another one
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>Unit</code> - result of dividing this unit by the other unit
| Param | Type |
| --- | --- |
| other | <code>Unit</code> |
<a name="Unit+pow"></a>
### unit.pow(p) ⇒ <code>Unit</code>
Calculate the power of a unit
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>Unit</code> - The result: this^p
| Param | Type |
| --- | --- |
| p | <code>number</code> &#124; <code>Fraction</code> &#124; <code>BigNumber</code> |
<a name="Unit+abs"></a>
### unit.abs(x) ⇒ <code>Unit</code>
Calculate the absolute value of a unit
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>Unit</code> - The result: |x|, absolute value of x
| Param | Type |
| --- | --- |
| x | <code>number</code> &#124; <code>Fraction</code> &#124; <code>BigNumber</code> |
<a name="Unit+to"></a>
### unit.to(valuelessUnit) ⇒ <code>Unit</code>
Convert the unit to a specific unit name.
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>Unit</code> - Returns a clone of the unit with a fixed prefix and unit.
| Param | Type | Description |
| --- | --- | --- |
| valuelessUnit | <code>string</code> &#124; <code>Unit</code> | A unit without value. Can have prefix, like "cm" |
<a name="Unit+toNumber"></a>
### unit.toNumber(valuelessUnit) ⇒ <code>number</code>
Return the value of the unit when represented with given valueless unit
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>number</code> - Returns the unit value as number.
| Param | Type | Description |
| --- | --- | --- |
| valuelessUnit | <code>string</code> &#124; <code>Unit</code> | For example 'cm' or 'inch' |
<a name="Unit+toNumeric"></a>
### unit.toNumeric(valuelessUnit) ⇒ <code>number</code> &#124; <code>BigNumber</code> &#124; <code>Fraction</code>
Return the value of the unit in the original numeric type
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>number</code> &#124; <code>BigNumber</code> &#124; <code>Fraction</code> - Returns the unit value
| Param | Type | Description |
| --- | --- | --- |
| valuelessUnit | <code>string</code> &#124; <code>Unit</code> | For example 'cm' or 'inch' |
<a name="Unit+toString"></a>
### unit.toString() ⇒ <code>string</code>
Get a string representation of the unit.
**Kind**: instance method of <code>Unit</code>
<a name="Unit+toJSON"></a>
### unit.toJSON() ⇒ <code>Object</code>
Get a JSON representation of the unit
**Kind**: instance method of <code>Unit</code>
**Returns**: <code>Object</code> - Returns a JSON object structured as:
`{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}`
<a name="Unit+formatUnits"></a>
### unit.formatUnits() ⇒ <code>string</code>
Get a string representation of the units of this Unit, without the value.
**Kind**: instance method of <code>Unit</code>
<a name="Unit+format"></a>
### unit.format([options]) ⇒ <code>string</code>
Get a string representation of the Unit, with optional formatting options.
**Kind**: instance method of <code>Unit</code>
| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>Object</code> &#124; <code>number</code> &#124; <code>function</code> | Formatting options. See lib/utils/number:format for a description of the available options. |
<a name="Unit.parse"></a>
### Unit.parse(str) ⇒ <code>Unit</code>
Parse a string into a unit. The value of the unit is parsed as number,
BigNumber, or Fraction depending on the math.js config setting `number`.
Throws an exception if the provided string does not contain a valid unit or
cannot be parsed.
**Kind**: static method of <code>Unit</code>
**Returns**: <code>Unit</code> - unit
| Param | Type | Description |
| --- | --- | --- |
| str | <code>string</code> | A string like "5.2 inch", "4e2 cm/s^2" |
<a name="Unit.isValuelessUnit"></a>
### Unit.isValuelessUnit(name) ⇒ <code>boolean</code>
Test if the given expression is a unit.
The unit can have a prefix but cannot have a value.
**Kind**: static method of <code>Unit</code>
**Returns**: <code>boolean</code> - true if the given string is a unit
| Param | Type | Description |
| --- | --- | --- |
| name | <code>string</code> | A string to be tested whether it is a value less unit. The unit can have prefix, like "cm" |
<a name="Unit.fromJSON"></a>
### Unit.fromJSON(json) ⇒ <code>Unit</code>
Instantiate a Unit from a JSON object
**Kind**: static method of <code>Unit</code>
| Param | Type | Description |
| --- | --- | --- |
| json | <code>Object</code> | A JSON object structured as: `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}` |

View File

@@ -0,0 +1,29 @@
# Constant reference
Math.js contains the following constants.
Constant | Description | Value
--------------- | ----------- | -----
`e`, `E` | Euler's number, the base of the natural logarithm. | 2.718281828459045
`i` | Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part. | `sqrt(-1)`
`Infinity` | Infinity, a number which is larger than the maximum number that can be handled by a floating point number. | `Infinity`
`LN2` | Returns the natural logarithm of 2. | `0.6931471805599453`
`LN10` | Returns the natural logarithm of 10. | `2.302585092994046`
`LOG2E` | Returns the base-2 logarithm of E. | `1.4426950408889634`
`LOG10E` | Returns the base-10 logarithm of E. | `0.4342944819032518`
`NaN` | Not a number. | `NaN`
`null` | Value null. | `null`
`phi` | Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` | `1.618033988749895`
`pi`, `PI` | The number pi is a mathematical constant that is the ratio of a circle\'s circumference to its diameter. | `3.141592653589793`
`SQRT1_2` | Returns the square root of 1/2. | `0.7071067811865476`
`SQRT2` | Returns the square root of 2. | `1.4142135623730951`
`tau` | Tau is the ratio constant of a circle\'s circumference to radius, equal to `2 * pi`. | `6.283185307179586`
`uninitialized` | Constant used as default value when resizing a matrix to leave new entries uninitialized.
`version` | Returns the version number of math.js. | For example `0.24.1`
Example usage:
```js
math.sin(math.pi / 4); // 0.70711
math.multiply(math.i, math.i); // -1
```

View File

@@ -0,0 +1,267 @@
# Function reference
## Core functions
Function | Description
---- | -----------
[math.config(config:&nbsp;Object):&nbsp;Object](functions/config.md) | Set configuration options for math.
[math.typed(name,&nbsp;signatures)&nbsp;:&nbsp;function](functions/typed.md) | Create a typed-function which checks the types of the arguments and can match them against multiple provided signatures.
## Construction functions
Function | Description
---- | -----------
[math.bignumber(x)](functions/bignumber.md) | Create a BigNumber, which can store numbers with arbitrary precision.
[math.boolean(x)](functions/boolean.md) | Create a boolean or convert a string or number to a boolean.
[math.chain(value)](functions/chain.md) | Wrap any value in a chain, allowing to perform chained operations on the value.
[math.complex(re,&nbsp;im)](functions/complex.md) | Create a complex value or convert a value to a complex value.
[math.createUnit(units)](functions/createUnit.md) | Create a user-defined unit and register it with the Unit type.
[math.fraction(numerator,&nbsp;denominator)](functions/fraction.md) | Create a fraction convert a value to a fraction.
[math.index(range1,&nbsp;range2,&nbsp;...)](functions/index.md) | Create an index.
[math.matrix(x)](functions/matrix.md) | Create a Matrix.
[math.number(value)](functions/number.md) | Create a number or convert a string, boolean, or unit to a number.
[math.sparse(x)](functions/sparse.md) | Create a Sparse Matrix.
[math.splitUnit(unit,&nbsp;parts)](functions/splitUnit.md) | Split a unit in an array of units whose sum is equal to the original unit.
[math.string(value)](functions/string.md) | Create a string or convert any object into a string.
[math.unit(x)](functions/unit.md) | Create a unit.
## Expression functions
Function | Description
---- | -----------
[math.compile(expr)](functions/compile.md) | Parse and compile an expression.
[math.eval(expr&nbsp;[,&nbsp;scope])](functions/eval.md) | Evaluate an expression.
[math.help(search)](functions/help.md) | Retrieve help on a function or data type.
[math.parse(expr&nbsp;[,&nbsp;scope])](functions/parse.md) | Parse an expression.
[math.parser()](functions/parser.md) | Create a parser.
## Algebra functions
Function | Description
---- | -----------
[derivative(expr,&nbsp;variable)](functions/derivative.md) | Takes the derivative of an expression expressed in parser Nodes.
[math.lsolve(L,&nbsp;b)](functions/lsolve.md) | Solves the linear equation system by forwards substitution.
[math.lup(A)](functions/lup.md) | Calculate the Matrix LU decomposition with partial pivoting.
[math.lusolve(A,&nbsp;b)](functions/lusolve.md) | Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector.
[simplify(expr)](functions/simplify.md) | Simplify an expression tree.
[math.slu(A,&nbsp;order,&nbsp;threshold)](functions/slu.md) | Calculate the Sparse Matrix LU decomposition with full pivoting.
[math.usolve(U,&nbsp;b)](functions/usolve.md) | Solves the linear equation system by backward substitution.
## Arithmetic functions
Function | Description
---- | -----------
[math.abs(x)](functions/abs.md) | Calculate the absolute value of a number.
[math.add(x,&nbsp;y)](functions/add.md) | Add two or more values, `x + y`.
[math.cbrt(x&nbsp;[,&nbsp;allRoots])](functions/cbrt.md) | Calculate the cubic root of a value.
[math.ceil(x)](functions/ceil.md) | Round a value towards plus infinity If `x` is complex, both real and imaginary part are rounded towards plus infinity.
[math.cube(x)](functions/cube.md) | Compute the cube of a value, `x * x * x`.
[math.divide(x,&nbsp;y)](functions/divide.md) | Divide two values, `x / y`.
[math.dotDivide(x,&nbsp;y)](functions/dotDivide.md) | Divide two matrices element wise.
[math.dotMultiply(x,&nbsp;y)](functions/dotMultiply.md) | Multiply two matrices element wise.
[math.dotPow(x,&nbsp;y)](functions/dotPow.md) | Calculates the power of x to y element wise.
[math.exp(x)](functions/exp.md) | Calculate the exponent of a value.
[math.fix(x)](functions/fix.md) | Round a value towards zero.
[math.floor(x)](functions/floor.md) | Round a value towards minus infinity.
[math.gcd(a,&nbsp;b)](functions/gcd.md) | Calculate the greatest common divisor for two or more values or arrays.
[math.hypot(a,&nbsp;b,&nbsp;...)](functions/hypot.md) | Calculate the hypotenusa of a list with values.
[math.lcm(a,&nbsp;b)](functions/lcm.md) | Calculate the least common multiple for two or more values or arrays.
[math.log(x&nbsp;[,&nbsp;base])](functions/log.md) | Calculate the logarithm of a value.
[math.log10(x)](functions/log10.md) | Calculate the 10-base logarithm of a value.
[math.mod(x,&nbsp;y)](functions/mod.md) | Calculates the modulus, the remainder of an integer division.
[math.multiply(x,&nbsp;y)](functions/multiply.md) | Multiply two or more values, `x * y`.
[math.norm(x&nbsp;[,&nbsp;p])](functions/norm.md) | Calculate the norm of a number, vector or matrix.
[math.nthRoot(a)](functions/nthRoot.md) | Calculate the nth root of a value.
[math.pow(x,&nbsp;y)](functions/pow.md) | Calculates the power of x to y, `x ^ y`.
[math.round(x&nbsp;[,&nbsp;n])](functions/round.md) | Round a value towards the nearest integer.
[math.sign(x)](functions/sign.md) | Compute the sign of a value.
[math.sqrt(x)](functions/sqrt.md) | Calculate the square root of a value.
[math.square(x)](functions/square.md) | Compute the square of a value, `x * x`.
[math.subtract(x,&nbsp;y)](functions/subtract.md) | Subtract two values, `x - y`.
[math.unaryMinus(x)](functions/unaryMinus.md) | Inverse the sign of a value, apply a unary minus operation.
[math.unaryPlus(x)](functions/unaryPlus.md) | Unary plus operation.
[math.xgcd(a,&nbsp;b)](functions/xgcd.md) | Calculate the extended greatest common divisor for two values.
## Bitwise functions
Function | Description
---- | -----------
[math.bitAnd(x,&nbsp;y)](functions/bitAnd.md) | Bitwise AND two values, `x & y`.
[math.bitNot(x)](functions/bitNot.md) | Bitwise NOT value, `~x`.
[math.bitOr(x,&nbsp;y)](functions/bitOr.md) | Bitwise OR two values, `x | y`.
[math.bitXor(x,&nbsp;y)](functions/bitXor.md) | Bitwise XOR two values, `x ^ y`.
[math.leftShift(x,&nbsp;y)](functions/leftShift.md) | Bitwise left logical shift of a value x by y number of bits, `x << y`.
[math.rightArithShift(x,&nbsp;y)](functions/rightArithShift.md) | Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`.
[math.rightLogShift(x,&nbsp;y)](functions/rightLogShift.md) | Bitwise right logical shift of value x by y number of bits, `x >>> y`.
## Combinatorics functions
Function | Description
---- | -----------
[math.bellNumbers(n)](functions/bellNumbers.md) | The Bell Numbers count the number of partitions of a set.
[math.catalan(n)](functions/catalan.md) | The Catalan Numbers enumerate combinatorial structures of many different types.
[math.composition(n,&nbsp;k)](functions/composition.md) | The composition counts of n into k parts.
[math.stirlingS2(n,&nbsp;k)](functions/stirlingS2.md) | The Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets.
## Complex functions
Function | Description
---- | -----------
[math.arg(x)](functions/arg.md) | Compute the argument of a complex value.
[math.conj(x)](functions/conj.md) | Compute the complex conjugate of a complex value.
[math.im(x)](functions/im.md) | Get the imaginary part of a complex number.
[math.re(x)](functions/re.md) | Get the real part of a complex number.
## Geometry functions
Function | Description
---- | -----------
[math.distance([x1,&nbsp;y1],&nbsp;[x2,&nbsp;y2])](functions/distance.md) | Calculates: The eucledian distance between two points in 2 and 3 dimensional spaces.
[math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2)](functions/intersect.md) | Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in three dimensions.
## Logical functions
Function | Description
---- | -----------
[math.and(x,&nbsp;y)](functions/and.md) | Logical `and`.
[math.not(x)](functions/not.md) | Logical `not`.
[math.or(x,&nbsp;y)](functions/or.md) | Logical `or`.
[math.xor(x,&nbsp;y)](functions/xor.md) | Logical `xor`.
## Matrix functions
Function | Description
---- | -----------
[math.concat(a,&nbsp;b,&nbsp;c,&nbsp;...&nbsp;[,&nbsp;dim])](functions/concat.md) | Concatenate two or more matrices.
[math.cross(x,&nbsp;y)](functions/cross.md) | Calculate the cross product for two vectors in three dimensional space.
[math.det(x)](functions/det.md) | Calculate the determinant of a matrix.
[math.diag(X)](functions/diag.md) | Create a diagonal matrix or retrieve the diagonal of a matrix When `x` is a vector, a matrix with vector `x` on the diagonal will be returned.
[math.dot(x,&nbsp;y)](functions/dot.md) | Calculate the dot product of two vectors.
[math.eye(n)](functions/eye.md) | Create a 2-dimensional identity matrix with size m x n or n x n.
[math.filter(x,&nbsp;test)](functions/filter.md) | Filter the items in an array or one dimensional matrix.
[math.flatten(x)](functions/flatten.md) | Flatten a multi dimensional matrix into a single dimensional matrix.
[math.forEach(x,&nbsp;callback)](functions/forEach.md) | Iterate over all elements of a matrix/array, and executes the given callback function.
[math.inv(x)](functions/inv.md) | Calculate the inverse of a square matrix.
[math.kron(x,&nbsp;y)](functions/kron.md) | Calculates the kronecker product of 2 matrices or vectors.
[math.map(x,&nbsp;callback)](functions/map.md) | Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.
[math.ones(m,&nbsp;n,&nbsp;p,&nbsp;...)](functions/ones.md) | Create a matrix filled with ones.
[math.partitionSelect(x,&nbsp;k)](functions/partitionSelect.md) | Partition-based selection of an array or 1D matrix.
[math.range(start,&nbsp;end&nbsp;[,&nbsp;step])](functions/range.md) | Create an array from a range.
[math.resize(x,&nbsp;size&nbsp;[,&nbsp;defaultValue])](functions/resize.md) | Resize a matrix.
[math.size(x)](functions/size.md) | Calculate the size of a matrix or scalar.
[math.sort(x)](functions/sort.md) | Sort the items in a matrix.
[math.squeeze(x)](functions/squeeze.md) | Squeeze a matrix, remove inner and outer singleton dimensions from a matrix.
[math.subset(x,&nbsp;index&nbsp;[,&nbsp;replacement])](functions/subset.md) | Get or set a subset of a matrix or string.
[math.trace(x)](functions/trace.md) | Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.
[math.transpose(x)](functions/transpose.md) | Transpose a matrix.
[math.zeros(m,&nbsp;n,&nbsp;p,&nbsp;...)](functions/zeros.md) | Create a matrix filled with zeros.
## Probability functions
Function | Description
---- | -----------
[math.combinations(n,&nbsp;k)](functions/combinations.md) | Compute the number of ways of picking `k` unordered outcomes from `n` possibilities.
[math.factorial(n)](functions/factorial.md) | Compute the factorial of a value Factorial only supports an integer value as argument.
[math.gamma(n)](functions/gamma.md) | Compute the gamma function of a value using Lanczos approximation for small values, and an extended Stirling approximation for large values.
[math.kldivergence(x,&nbsp;y)](functions/kldivergence.md) | Calculate the Kullback-Leibler (KL) divergence between two distributions.
[math.multinomial(a)](functions/multinomial.md) | Multinomial Coefficients compute the number of ways of picking a1, a2, .
[math.permutations(n&nbsp;[,&nbsp;k])](functions/permutations.md) | Compute the number of ways of obtaining an ordered subset of `k` elements from a set of `n` elements.
[math.pickRandom(array)](functions/pickRandom.md) | Random pick one or more values from a one dimensional array.
[math.random([min,&nbsp;max])](functions/random.md) | Return a random number larger or equal to `min` and smaller than `max` using a uniform distribution.
[math.randomInt([min,&nbsp;max])](functions/randomInt.md) | Return a random integer number larger or equal to `min` and smaller than `max` using a uniform distribution.
## Relational functions
Function | Description
---- | -----------
[math.compare(x,&nbsp;y)](functions/compare.md) | Compare two values.
[math.deepEqual(x,&nbsp;y)](functions/deepEqual.md) | Test element wise whether two matrices are equal.
[math.equal(x,&nbsp;y)](functions/equal.md) | Test whether two values are equal.
[math.larger(x,&nbsp;y)](functions/larger.md) | Test whether value x is larger than y.
[math.largerEq(x,&nbsp;y)](functions/largerEq.md) | Test whether value x is larger or equal to y.
[math.smaller(x,&nbsp;y)](functions/smaller.md) | Test whether value x is smaller than y.
[math.smallerEq(x,&nbsp;y)](functions/smallerEq.md) | Test whether value x is smaller or equal to y.
[math.unequal(x,&nbsp;y)](functions/unequal.md) | Test whether two values are unequal.
## Special functions
Function | Description
---- | -----------
[math.erf(x)](functions/erf.md) | Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x.
## Statistics functions
Function | Description
---- | -----------
[math.mad(a,&nbsp;b,&nbsp;c,&nbsp;...)](functions/mad.md) | Compute the median absolute deviation of a matrix or a list with values.
[math.max(a,&nbsp;b,&nbsp;c,&nbsp;...)](functions/max.md) | Compute the maximum value of a matrix or a list with values.
[math.mean(a,&nbsp;b,&nbsp;c,&nbsp;...)](functions/mean.md) | Compute the mean value of matrix or a list with values.
[math.median(a,&nbsp;b,&nbsp;c,&nbsp;...)](functions/median.md) | Compute the median of a matrix or a list with values.
[math.min(a,&nbsp;b,&nbsp;c,&nbsp;...)](functions/min.md) | Compute the maximum value of a matrix or a list of values.
[math.mode(a,&nbsp;b,&nbsp;c,&nbsp;...)](functions/mode.md) | Computes the mode of a set of numbers or a list with values(numbers or characters).
[math.prod(a,&nbsp;b,&nbsp;c,&nbsp;...)](functions/prod.md) | Compute the product of a matrix or a list with values.
[math.quantileSeq(A,&nbsp;prob[,&nbsp;sorted])](functions/quantileSeq.md) | Compute the prob order quantile of a matrix or a list with values.
[math.std(a,&nbsp;b,&nbsp;c,&nbsp;...)](functions/std.md) | Compute the standard deviation of a matrix or a list with values.
[math.sum(a,&nbsp;b,&nbsp;c,&nbsp;...)](functions/sum.md) | Compute the sum of a matrix or a list with values.
[math.var(a,&nbsp;b,&nbsp;c,&nbsp;...)](functions/var.md) | Compute the variance of a matrix or a list with values.
## String functions
Function | Description
---- | -----------
[math.format(value&nbsp;[,&nbsp;precision])](functions/format.md) | Format a value of any type into a string.
[math.print(template, values [, precision])](functions/print.md) | Interpolate values into a string template.
## Trigonometry functions
Function | Description
---- | -----------
[math.acos(x)](functions/acos.md) | Calculate the inverse cosine of a value.
[math.acosh(x)](functions/acosh.md) | Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
[math.acot(x)](functions/acot.md) | Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`.
[math.acoth(x)](functions/acoth.md) | Calculate the hyperbolic arccotangent of a value, defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.
[math.acsc(x)](functions/acsc.md) | Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`.
[math.acsch(x)](functions/acsch.md) | Calculate the hyperbolic arccosecant of a value, defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`.
[math.asec(x)](functions/asec.md) | Calculate the inverse secant of a value.
[math.asech(x)](functions/asech.md) | Calculate the hyperbolic arcsecant of a value, defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`.
[math.asin(x)](functions/asin.md) | Calculate the inverse sine of a value.
[math.asinh(x)](functions/asinh.md) | Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.
[math.atan(x)](functions/atan.md) | Calculate the inverse tangent of a value.
[math.atan2(y,&nbsp;x)](functions/atan2.md) | Calculate the inverse tangent function with two arguments, y/x.
[math.atanh(x)](functions/atanh.md) | Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.
[math.cos(x)](functions/cos.md) | Calculate the cosine of a value.
[math.cosh(x)](functions/cosh.md) | Calculate the hyperbolic cosine of a value, defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
[math.cot(x)](functions/cot.md) | Calculate the cotangent of a value.
[math.coth(x)](functions/coth.md) | Calculate the hyperbolic cotangent of a value, defined as `coth(x) = 1 / tanh(x)`.
[math.csc(x)](functions/csc.md) | Calculate the cosecant of a value, defined as `csc(x) = 1/sin(x)`.
[math.csch(x)](functions/csch.md) | Calculate the hyperbolic cosecant of a value, defined as `csch(x) = 1 / sinh(x)`.
[math.sec(x)](functions/sec.md) | Calculate the secant of a value, defined as `sec(x) = 1/cos(x)`.
[math.sech(x)](functions/sech.md) | Calculate the hyperbolic secant of a value, defined as `sech(x) = 1 / cosh(x)`.
[math.sin(x)](functions/sin.md) | Calculate the sine of a value.
[math.sinh(x)](functions/sinh.md) | Calculate the hyperbolic sine of a value, defined as `sinh(x) = 1/2 * (exp(x) - exp(-x))`.
[math.tan(x)](functions/tan.md) | Calculate the tangent of a value.
[math.tanh(x)](functions/tanh.md) | Calculate the hyperbolic tangent of a value, defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`.
## Unit functions
Function | Description
---- | -----------
[math.to(x,&nbsp;unit)](functions/to.md) | Change the unit of a value.
## Utils functions
Function | Description
---- | -----------
[math.clone(x)](functions/clone.md) | Clone an object.
[math.isInteger(x)](functions/isInteger.md) | Test whether a value is an integer number.
[math.isNaN(x)](functions/isNaN.md) | Test whether a value is NaN (not a number).
[math.isNegative(x)](functions/isNegative.md) | Test whether a value is negative: smaller than zero.
[math.isNumeric(x)](functions/isNumeric.md) | Test whether a value is an numeric value.
[math.isPositive(x)](functions/isPositive.md) | Test whether a value is positive: larger than zero.
[math.isPrime(x)](functions/isPrime.md) | Test whether a value is prime: has no divisors other than itself and one.
[math.isZero(x)](functions/isZero.md) | Test whether a value is zero.
[math.typeof(x)](functions/typeof.md) | Determine the type of a variable.
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->

View File

@@ -0,0 +1,40 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function abs
Calculate the absolute value of a number. For matrices, the function is
evaluated element wise.
## Syntax
```js
math.abs(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Array &#124; Matrix &#124; Unit | A number or matrix for which to get the absolute value
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Array &#124; Matrix &#124; Unit | Absolute value of `x`
## Examples
```js
math.abs(3.5); // returns number 3.5
math.abs(-4.2); // returns number 4.2
math.abs([3, -5, -1, 0, 2]); // returns Array [3, 5, 1, 0, 2]
```
## See also
[sign](sign.md)

View File

@@ -0,0 +1,43 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function acos
Calculate the inverse cosine of a value.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.acos(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | The arc cosine of x
## Examples
```js
math.acos(0.5); // returns number 1.0471975511965979
math.acos(math.cos(1.5)); // returns number 1.5
math.acos(2); // returns Complex 0 + 1.3169578969248166 i
```
## See also
[cos](cos.md),
[atan](atan.md),
[asin](asin.md)

View File

@@ -0,0 +1,41 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function acosh
Calculate the hyperbolic arccos of a value,
defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.acosh(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | Hyperbolic arccosine of x
## Examples
```js
math.acosh(1.5); // returns 0.9624236501192069
```
## See also
[cosh](cosh.md),
[asinh](asinh.md),
[atanh](atanh.md)

View File

@@ -0,0 +1,42 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function acot
Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.acot(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | The arc cotangent of x
## Examples
```js
math.acot(0.5); // returns number 0.4636476090008061
math.acot(math.cot(1.5)); // returns number 1.5
math.acot(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
```
## See also
[cot](cot.md),
[atan](atan.md)

View File

@@ -0,0 +1,40 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function acoth
Calculate the hyperbolic arccotangent of a value,
defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.acoth(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | Hyperbolic arccotangent of x
## Examples
```js
math.acoth(0.5); // returns 0.8047189562170503
```
## See also
[acsch](acsch.md),
[asech](asech.md)

View File

@@ -0,0 +1,43 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function acsc
Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.acsc(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | The arc cosecant of x
## Examples
```js
math.acsc(0.5); // returns number 0.5235987755982989
math.acsc(math.csc(1.5)); // returns number ~1.5
math.acsc(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
```
## See also
[csc](csc.md),
[asin](asin.md),
[asec](asec.md)

View File

@@ -0,0 +1,40 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function acsch
Calculate the hyperbolic arccosecant of a value,
defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.acsch(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | Hyperbolic arccosecant of x
## Examples
```js
math.acsch(0.5); // returns 1.4436354751788103
```
## See also
[asech](asech.md),
[acoth](acoth.md)

View File

@@ -0,0 +1,53 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function add
Add two or more values, `x + y`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.add(x, y)
math.add(x, y, z, ...)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | First value to add
`y` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Second value to add
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Sum of `x` and `y`
## Examples
```js
math.add(2, 3); // returns number 5
math.add(2, 3, 4); // returns number 9
var a = math.complex(2, 3);
var b = math.complex(-4, 1);
math.add(a, b); // returns Complex -2 + 4i
math.add([1, 2, 3], 4); // returns Array [5, 6, 7]
var c = math.unit('5 cm');
var d = math.unit('2.1 mm');
math.add(c, d); // returns Unit 52.1 mm
math.add("2.3", "4"); // returns number 6.3
```
## See also
[subtract](subtract.md),
[sum](sum.md)

View File

@@ -0,0 +1,47 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function and
Logical `and`. Test whether two values are both defined with a nonzero/nonempty value.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.and(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Complex &#124; Unit &#124; Array &#124; Matrix | First value to check
`y` | number &#124; BigNumber &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Second value to check
### Returns
Type | Description
---- | -----------
boolean &#124; Array &#124; Matrix | Returns true when both inputs are defined with a nonzero/nonempty value.
## Examples
```js
math.and(2, 4); // returns true
a = [2, 0, 0];
b = [3, 7, 0];
c = 0;
math.and(a, b); // returns [true, false, false]
math.and(a, c); // returns [false, false, false]
```
## See also
[not](not.md),
[or](or.md),
[xor](xor.md)

View File

@@ -0,0 +1,47 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function arg
Compute the argument of a complex value.
For a complex number `a + bi`, the argument is computed as `atan2(b, a)`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.arg(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | A complex number or array with complex numbers
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Array &#124; Matrix | The argument of x
## Examples
```js
var a = math.complex(2, 2);
math.arg(a) / math.pi; // returns number 0.25
var b = math.complex('2 + 3i');
math.arg(b); // returns number 0.982793723247329
math.atan2(3, 2); // returns number 0.982793723247329
```
## See also
[re](re.md),
[im](im.md),
[conj](conj.md),
[abs](abs.md)

View File

@@ -0,0 +1,43 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function asec
Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.asec(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | The arc secant of x
## Examples
```js
math.asec(0.5); // returns 1.0471975511965979
math.asec(math.sec(1.5)); // returns 1.5
math.asec(2); // returns 0 + 1.3169578969248166 i
```
## See also
[acos](acos.md),
[acot](acot.md),
[acsc](acsc.md)

View File

@@ -0,0 +1,40 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function asech
Calculate the hyperbolic arcsecant of a value,
defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.asech(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | Hyperbolic arcsecant of x
## Examples
```js
math.asech(0.5); // returns 1.3169578969248166
```
## See also
[acsch](acsch.md),
[acoth](acoth.md)

View File

@@ -0,0 +1,43 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function asin
Calculate the inverse sine of a value.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.asin(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | The arc sine of x
## Examples
```js
math.asin(0.5); // returns number 0.5235987755982989
math.asin(math.sin(1.5)); // returns number ~1.5
math.asin(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
```
## See also
[sin](sin.md),
[atan](atan.md),
[acos](acos.md)

View File

@@ -0,0 +1,40 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function asinh
Calculate the hyperbolic arcsine of a value,
defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.asinh(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | Hyperbolic arcsine of x
## Examples
```js
math.asinh(0.5); // returns 0.48121182505960347
```
## See also
[acosh](acosh.md),
[atanh](atanh.md)

View File

@@ -0,0 +1,43 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function atan
Calculate the inverse tangent of a value.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.atan(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | The arc tangent of x
## Examples
```js
math.atan(0.5); // returns number 0.4636476090008061
math.atan(math.tan(1.5)); // returns number 1.5
math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
```
## See also
[tan](tan.md),
[asin](asin.md),
[acos](acos.md)

View File

@@ -0,0 +1,50 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function atan2
Calculate the inverse tangent function with two arguments, y/x.
By providing two arguments, the right quadrant of the computed angle can be
determined.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.atan2(y, x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`y` | number &#124; Array &#124; Matrix | Second dimension
`x` | number &#124; Array &#124; Matrix | First dimension
### Returns
Type | Description
---- | -----------
number &#124; Array &#124; Matrix | Four-quadrant inverse tangent
## Examples
```js
math.atan2(2, 2) / math.pi; // returns number 0.25
var angle = math.unit(60, 'deg'); // returns Unit 60 deg
var x = math.cos(angle);
var y = math.sin(angle);
math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
```
## See also
[tan](tan.md),
[atan](atan.md),
[sin](sin.md),
[cos](cos.md)

View File

@@ -0,0 +1,40 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function atanh
Calculate the hyperbolic arctangent of a value,
defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.atanh(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | Hyperbolic arctangent of x
## Examples
```js
math.atanh(0.5); // returns 0.5493061443340549
```
## See also
[acosh](acosh.md),
[asinh](asinh.md)

View File

@@ -0,0 +1,39 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function bellNumbers
The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S.
bellNumbers only takes integer arguments.
The following condition must be enforced: n >= 0
## Syntax
```js
math.bellNumbers(n)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`n` | Number &#124; BigNumber | Total number of objects in the set
### Returns
Type | Description
---- | -----------
Number &#124; BigNumber | B(n)
## Examples
```js
math.bellNumbers(3); // returns 5;
math.bellNumbers(8); // returns 4140;
```
## See also
[stirlingS2](stirlingS2.md)

View File

@@ -0,0 +1,47 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function bignumber
Create a BigNumber, which can store numbers with arbitrary precision.
When a matrix is provided, all elements will be converted to BigNumber.
## Syntax
```js
math.bignumber(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`value` | number &#124; string &#124; Fraction &#124; BigNumber &#124; Array &#124; Matrix &#124; boolean &#124; null | Value for the big number, 0 by default.
### Returns
Type | Description
---- | -----------
BigNumber | The created bignumber
## Examples
```js
0.1 + 0.2; // returns number 0.30000000000000004
math.bignumber(0.1) + math.bignumber(0.2); // returns BigNumber 0.3
7.2e500; // returns number Infinity
math.bignumber('7.2e500'); // returns BigNumber 7.2e500
```
## See also
[boolean](boolean.md),
[complex](complex.md),
[index](index.md),
[matrix](matrix.md),
[string](string.md),
[unit](unit.md)

View File

@@ -0,0 +1,45 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function bitAnd
Bitwise AND two values, `x & y`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.bitAnd(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Array &#124; Matrix | First value to and
`y` | number &#124; BigNumber &#124; Array &#124; Matrix | Second value to and
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Array &#124; Matrix | AND of `x` and `y`
## Examples
```js
math.bitAnd(53, 131); // returns number 1
math.bitAnd([1, 12, 31], 42); // returns Array [0, 8, 10]
```
## See also
[bitNot](bitNot.md),
[bitOr](bitOr.md),
[bitXor](bitXor.md),
[leftShift](leftShift.md),
[rightArithShift](rightArithShift.md),
[rightLogShift](rightLogShift.md)

View File

@@ -0,0 +1,45 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function bitNot
Bitwise NOT value, `~x`.
For matrices, the function is evaluated element wise.
For units, the function is evaluated on the best prefix base.
## Syntax
```js
math.bitNot(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Array &#124; Matrix | Value to not
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Array &#124; Matrix | NOT of `x`
## Examples
```js
math.bitNot(1); // returns number -2
math.bitNot([2, -3, 4]); // returns Array [-3, 2, 5]
```
## See also
[bitAnd](bitAnd.md),
[bitOr](bitOr.md),
[bitXor](bitXor.md),
[leftShift](leftShift.md),
[rightArithShift](rightArithShift.md),
[rightLogShift](rightLogShift.md)

View File

@@ -0,0 +1,46 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function bitOr
Bitwise OR two values, `x | y`.
For matrices, the function is evaluated element wise.
For units, the function is evaluated on the lowest print base.
## Syntax
```js
math.bitOr(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Array &#124; Matrix | First value to or
`y` | number &#124; BigNumber &#124; Array &#124; Matrix | Second value to or
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Array &#124; Matrix | OR of `x` and `y`
## Examples
```js
math.bitOr(1, 2); // returns number 3
math.bitOr([1, 2, 3], 4); // returns Array [5, 6, 7]
```
## See also
[bitAnd](bitAnd.md),
[bitNot](bitNot.md),
[bitXor](bitXor.md),
[leftShift](leftShift.md),
[rightArithShift](rightArithShift.md),
[rightLogShift](rightLogShift.md)

View File

@@ -0,0 +1,45 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function bitXor
Bitwise XOR two values, `x ^ y`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.bitXor(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Array &#124; Matrix | First value to xor
`y` | number &#124; BigNumber &#124; Array &#124; Matrix | Second value to xor
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Array &#124; Matrix | XOR of `x` and `y`
## Examples
```js
math.bitXor(1, 2); // returns number 3
math.bitXor([2, 3, 4], 4); // returns Array [6, 7, 0]
```
## See also
[bitAnd](bitAnd.md),
[bitNot](bitNot.md),
[bitOr](bitOr.md),
[leftShift](leftShift.md),
[rightArithShift](rightArithShift.md),
[rightLogShift](rightLogShift.md)

View File

@@ -0,0 +1,50 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function boolean
Create a boolean or convert a string or number to a boolean.
In case of a number, `true` is returned for non-zero numbers, and `false` in
case of zero.
Strings can be `'true'` or `'false'`, or can contain a number.
When value is a matrix, all elements will be converted to boolean.
## Syntax
```js
math.boolean(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`value` | string &#124; number &#124; boolean &#124; Array &#124; Matrix &#124; null | A value of any type
### Returns
Type | Description
---- | -----------
boolean &#124; Array &#124; Matrix | The boolean value
## Examples
```js
math.boolean(0); // returns false
math.boolean(1); // returns true
math.boolean(-3); // returns true
math.boolean('true'); // returns true
math.boolean('false'); // returns false
math.boolean([1, 0, 1, 1]); // returns [true, false, true, true]
```
## See also
[bignumber](bignumber.md),
[complex](complex.md),
[index](index.md),
[matrix](matrix.md),
[string](string.md),
[unit](unit.md)

View File

@@ -0,0 +1,39 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function catalan
The Catalan Numbers enumerate combinatorial structures of many different types.
catalan only takes integer arguments.
The following condition must be enforced: n >= 0
## Syntax
```js
math.catalan(n)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`n` | Number &#124; BigNumber | nth Catalan number
### Returns
Type | Description
---- | -----------
Number &#124; BigNumber | Cn(n)
## Examples
```js
math.catalan(3); // returns 5;
math.catalan(8); // returns 1430;
```
## See also
[bellNumbers](bellNumbers.md)

View File

@@ -0,0 +1,54 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function cbrt
Calculate the cubic root of a value.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.cbrt(x)
math.cbrt(x, allRoots)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Value for which to calculate the cubic root.
`allRoots` | boolean | Optional, false by default. Only applicable when `x` is a number or complex number. If true, all complex roots are returned, if false (default) the principal root is returned.
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Returns the cubic root of `x`
## Examples
```js
math.cbrt(27); // returns 3
math.cube(3); // returns 27
math.cbrt(-64); // returns -4
math.cbrt(math.unit('27 m^3')); // returns Unit 3 m
math.cbrt([27, 64, 125]); // returns [3, 4, 5]
var x = math.complex('8i');
math.cbrt(x); // returns Complex 1.7320508075689 + i
math.cbrt(x, true); // returns Matrix [
// 1.7320508075689 + i
// -1.7320508075689 + i
// -2i
// ]
```
## See also
[square](square.md),
[sqrt](sqrt.md),
[cube](cube.md)

View File

@@ -0,0 +1,48 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function ceil
Round a value towards plus infinity
If `x` is complex, both real and imaginary part are rounded towards plus infinity.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.ceil(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Array &#124; Matrix | Number to be rounded
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Array &#124; Matrix | Rounded value
## Examples
```js
math.ceil(3.2); // returns number 4
math.ceil(3.8); // returns number 4
math.ceil(-4.2); // returns number -4
math.ceil(-4.7); // returns number -4
var c = math.complex(3.2, -2.7);
math.ceil(c); // returns Complex 4 - 2i
math.ceil([3.2, 3.8, -4.7]); // returns Array [4, 4, -4]
```
## See also
[floor](floor.md),
[fix](fix.md),
[round](round.md)

View File

@@ -0,0 +1,54 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function chain
Wrap any value in a chain, allowing to perform chained operations on
the value.
All methods available in the math.js library can be called upon the chain,
and then will be evaluated with the value itself as first argument.
The chain can be closed by executing `chain.done()`, which returns
the final value.
The chain has a number of special functions:
- `done()` Finalize the chain and return the chain's value.
- `valueOf()` The same as `done()`
- `toString()` Executes `math.format()` onto the chain's value, returning
a string representation of the value.
## Syntax
```js
math.chain(value)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`value` | * | A value of any type on which to start a chained operation.
### Returns
Type | Description
---- | -----------
math.type.Chain | The created chain
## Examples
```js
math.chain(3)
.add(4)
.subtract(2)
.done(); // 5
math.chain( [[1, 2], [3, 4]] )
.subset(math.index(0, 0), 8)
.multiply(3)
.done(); // [[24, 6], [9, 12]]
```

View File

@@ -0,0 +1,37 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function clone
Clone an object.
## Syntax
```js
math.clone(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | * | Object to be cloned
### Returns
Type | Description
---- | -----------
* | A clone of object x
## Examples
```js
math.clone(3.5); // returns number 3.5
math.clone(math.complex('2-4i'); // returns Complex 2 - 4i
math.clone(math.unit(45, 'deg')); // returns Unit 45 deg
math.clone([[1, 2], [3, 4]]); // returns Array [[1, 2], [3, 4]]
math.clone("hello world"); // returns string "hello world"
```

View File

@@ -0,0 +1,42 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function combinations
Compute the number of ways of picking `k` unordered outcomes from `n`
possibilities.
Combinations only takes integer arguments.
The following condition must be enforced: k <= n.
## Syntax
```js
math.combinations(n, k)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`n` | number &#124; BigNumber | Total number of objects in the set
`k` | number &#124; BigNumber | Number of objects in the subset
### Returns
Type | Description
---- | -----------
number &#124; BigNumber | Number of possible combinations.
## Examples
```js
math.combinations(7, 5); // returns 21
```
## See also
[permutations](permutations.md),
[factorial](factorial.md)

View File

@@ -0,0 +1,56 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function compare
Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.
x and y are considered equal when the relative difference between x and y
is smaller than the configured epsilon. The function cannot be used to
compare values smaller than approximately 2.22e-16.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.compare(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Fraction &#124; Unit &#124; string &#124; Array &#124; Matrix | First value to compare
`y` | number &#124; BigNumber &#124; Fraction &#124; Unit &#124; string &#124; Array &#124; Matrix | Second value to compare
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Fraction &#124; Array &#124; Matrix | Returns the result of the comparison: 1, 0 or -1.
## Examples
```js
math.compare(6, 1); // returns 1
math.compare(2, 3); // returns -1
math.compare(7, 7); // returns 0
var a = math.unit('5 cm');
var b = math.unit('40 mm');
math.compare(a, b); // returns 1
math.compare(2, [1, 2, 3]); // returns [1, 0, -1]
```
## See also
[equal](equal.md),
[unequal](unequal.md),
[smaller](smaller.md),
[smallerEq](smallerEq.md),
[larger](larger.md),
[largerEq](largerEq.md)

View File

@@ -0,0 +1,50 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function compile
Parse and compile an expression.
Returns a an object with a function `eval([scope])` to evaluate the
compiled expression.
## Syntax
```js
math.compile(expr) // returns one node
math.compile([expr1, expr2, expr3, ...]) // returns an array with nodes
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`expr` | string &#124; string[] &#124; Array &#124; Matrix | The expression to be compiled
### Returns
Type | Description
---- | -----------
{eval: Function} &#124; Array.&lt;{eval: Function}&gt; | code An object with the compiled expression
## Examples
```js
var code = math.compile('sqrt(3^2 + 4^2)');
code.eval(); // 5
var scope = {a: 3, b: 4}
var code = math.compile('a * b'); // 12
code.eval(scope); // 12
scope.a = 5;
code.eval(scope); // 20
var nodes = math.compile(['a = 3', 'b = 4', 'a * b']);
nodes[2].eval(); // 12
```
## See also
[parse](parse.md),
[eval](eval.md)

View File

@@ -0,0 +1,61 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function complex
Create a complex value or convert a value to a complex value.
## Syntax
```js
math.complex() // creates a complex value with zero
// as real and imaginary part.
math.complex(re : number, im : string) // creates a complex value with provided
// values for real and imaginary part.
math.complex(re : number) // creates a complex value with provided
// real value and zero imaginary part.
math.complex(complex : Complex) // clones the provided complex value.
math.complex(arg : string) // parses a string into a complex value.
math.complex(array : Array) // converts the elements of the array
// or matrix element wise into a
// complex value.
math.complex({re: number, im: number}) // creates a complex value with provided
// values for real an imaginary part.
math.complex({r: number, phi: number}) // creates a complex value with provided
// polar coordinates
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`args` | * &#124; Array &#124; Matrix | Arguments specifying the real and imaginary part of the complex number
### Returns
Type | Description
---- | -----------
Complex &#124; Array &#124; Matrix | Returns a complex value
## Examples
```js
var a = math.complex(3, -4); // a = Complex 3 - 4i
a.re = 5; // a = Complex 5 - 4i
var i = a.im; // Number -4;
var b = math.complex('2 + 6i'); // Complex 2 + 6i
var c = math.complex(); // Complex 0 + 0i
var d = math.add(a, b); // Complex 5 + 2i
```
## See also
[bignumber](bignumber.md),
[boolean](boolean.md),
[index](index.md),
[matrix](matrix.md),
[number](number.md),
[string](string.md),
[unit](unit.md)

View File

@@ -0,0 +1,40 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function composition
The composition counts of n into k parts.
composition only takes integer arguments.
The following condition must be enforced: k <= n.
## Syntax
```js
math.composition(n, k)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`n` | Number &#124; BigNumber | Total number of objects in the set
`k` | Number &#124; BigNumber | Number of objects in the subset
### Returns
Type | Description
---- | -----------
Number &#124; BigNumber | Returns the composition counts of n into k parts.
## Examples
```js
math.composition(5, 3); // returns 6
```
## See also
[combinations](combinations.md)

View File

@@ -0,0 +1,50 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function concat
Concatenate two or more matrices.
## Syntax
```js
math.concat(A, B, C, ...)
math.concat(A, B, C, ..., dim)
```
### Where
- `dim: number` is a zero-based dimension over which to concatenate the matrices.
By default the last dimension of the matrices.
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`args` | ... Array &#124; Matrix | Two or more matrices
### Returns
Type | Description
---- | -----------
Array &#124; Matrix | Concatenated matrix
## Examples
```js
var A = [[1, 2], [5, 6]];
var B = [[3, 4], [7, 8]];
math.concat(A, B); // returns [[1, 2, 3, 4], [5, 6, 7, 8]]
math.concat(A, B, 0); // returns [[1, 2], [5, 6], [3, 4], [7, 8]]
math.concat('hello', ' ', 'world'); // returns 'hello world'
```
## See also
[size](size.md),
[squeeze](squeeze.md),
[subset](subset.md),
[transpose](transpose.md)

View File

@@ -0,0 +1,37 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function config
Set configuration options for math.js, and get current options.
Will emit a 'config' event, with arguments (curr, prev).
## Syntax
```js
math.config(config: Object): Object
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`options` | Object | Available options: {number} epsilon Minimum relative difference between two compared values, used by all comparison functions. {string} matrix A string 'Matrix' (default) or 'Array'. {string} number A string 'number' (default), 'BigNumber', or 'Fraction' {number} precision The number of significant digits for BigNumbers. Not applicable for Numbers. {string} parenthesis How to display parentheses in LaTeX and string output.
### Returns
Type | Description
---- | -----------
Object | Returns the current configuration
## Examples
```js
math.config().number; // outputs 'number'
math.eval('0.4'); // outputs number 0.4
math.config({number: 'Fraction'});
math.eval('0.4'); // outputs Fraction 2/5
```

View File

@@ -0,0 +1,44 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function conj
Compute the complex conjugate of a complex value.
If `x = a+bi`, the complex conjugate of `x` is `a - bi`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.conj(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | A complex number or array with complex numbers
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | The complex conjugate of x
## Examples
```js
math.conj(math.complex('2 + 3i')); // returns Complex 2 - 3i
math.conj(math.complex('2 - 3i')); // returns Complex 2 + 3i
math.conj(math.complex('-5.2i')); // returns Complex 5.2i
```
## See also
[re](re.md),
[im](im.md),
[arg](arg.md),
[abs](abs.md)

View File

@@ -0,0 +1,45 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function cos
Calculate the cosine of a value.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.cos(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | Cosine of x
## Examples
```js
math.cos(2); // returns number -0.4161468365471422
math.cos(math.pi / 4); // returns number 0.7071067811865475
math.cos(math.unit(180, 'deg')); // returns number -1
math.cos(math.unit(60, 'deg')); // returns number 0.5
var angle = 0.2;
math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2); // returns number ~1
```
## See also
[cos](cos.md),
[tan](tan.md)

View File

@@ -0,0 +1,40 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function cosh
Calculate the hyperbolic cosine of a value,
defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.cosh(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | Hyperbolic cosine of x
## Examples
```js
math.cosh(0.5); // returns number 1.1276259652063807
```
## See also
[sinh](sinh.md),
[tanh](tanh.md)

View File

@@ -0,0 +1,41 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function cot
Calculate the cotangent of a value. Defined as `cot(x) = 1 / tan(x)`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.cot(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | Cotangent of x
## Examples
```js
math.cot(2); // returns number -0.45765755436028577
1 / math.tan(2); // returns number -0.45765755436028577
```
## See also
[tan](tan.md),
[sec](sec.md),
[csc](csc.md)

View File

@@ -0,0 +1,43 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function coth
Calculate the hyperbolic cotangent of a value,
defined as `coth(x) = 1 / tanh(x)`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.coth(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | Hyperbolic cotangent of x
## Examples
```js
// coth(x) = 1 / tanh(x)
math.coth(2); // returns 1.0373147207275482
1 / math.tanh(2); // returns 1.0373147207275482
```
## See also
[sinh](sinh.md),
[tanh](tanh.md),
[cosh](cosh.md)

View File

@@ -0,0 +1,52 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function createUnit
Create a user-defined unit and register it with the Unit type.
## Syntax
```js
math.createUnit({
baseUnit1: {
aliases: [string, ...]
prefixes: object
},
unit2: {
definition: string,
aliases: [string, ...]
prefixes: object,
offset: number
},
unit3: string // Shortcut
})
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`name` | string | The name of the new unit. Must be unique. Example: 'knot'
`definition` | string, Unit | Definition of the unit in terms of existing units. For example, '0.514444444 m / s'.
`options` | Object | (optional) An object containing any of the following properties:
### Returns
Type | Description
---- | -----------
Unit | The new unit
## Examples
```js
math.createUnit('foo');
math.createUnit('knot', {definition: '0.514444444 m/s', aliases: ['knots', 'kt', 'kts']});
math.createUnit('mph', '1 mile/hour');
```
## See also
[unit](unit.md)

View File

@@ -0,0 +1,52 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function cross
Calculate the cross product for two vectors in three dimensional space.
The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined
as:
cross(A, B) = [
a2 * b3 - a3 * b2,
a3 * b1 - a1 * b3,
a1 * b2 - a2 * b1
]
If one of the input vectors has a dimension greater than 1, the output
vector will be a 1x3 (2-dimensional) matrix.
## Syntax
```js
math.cross(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | Array &#124; Matrix | First vector
`y` | Array &#124; Matrix | Second vector
### Returns
Type | Description
---- | -----------
Array &#124; Matrix | Returns the cross product of `x` and `y`
## Examples
```js
math.cross([1, 1, 0], [0, 1, 1]); // Returns [1, -1, 1]
math.cross([3, -3, 1], [4, 9, 2]); // Returns [-15, -2, 39]
math.cross([2, 3, 4], [5, 6, 7]); // Returns [-3, 6, -3]
math.cross([[1, 2, 3]], [[4], [5], [6]]); // Returns [[-3, 6, -3]]
```
## See also
[dot](dot.md),
[multiply](multiply.md)

View File

@@ -0,0 +1,41 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function csc
Calculate the cosecant of a value, defined as `csc(x) = 1/sin(x)`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.csc(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | Cosecant of x
## Examples
```js
math.csc(2); // returns number 1.099750170294617
1 / math.sin(2); // returns number 1.099750170294617
```
## See also
[sin](sin.md),
[sec](sec.md),
[cot](cot.md)

View File

@@ -0,0 +1,43 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function csch
Calculate the hyperbolic cosecant of a value,
defined as `csch(x) = 1 / sinh(x)`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.csch(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Function input
### Returns
Type | Description
---- | -----------
number &#124; Complex &#124; Array &#124; Matrix | Hyperbolic cosecant of x
## Examples
```js
// csch(x) = 1/ sinh(x)
math.csch(0.5); // returns 1.9190347513349437
1 / math.sinh(0.5); // returns 1.9190347513349437
```
## See also
[sinh](sinh.md),
[sech](sech.md),
[coth](coth.md)

View File

@@ -0,0 +1,45 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function cube
Compute the cube of a value, `x * x * x`.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.cube(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Array &#124; Matrix &#124; Unit | Number for which to calculate the cube
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Array &#124; Matrix &#124; Unit | Cube of x
## Examples
```js
math.cube(2); // returns number 8
math.pow(2, 3); // returns number 8
math.cube(4); // returns number 64
4 * 4 * 4; // returns number 64
math.cube([1, 2, 3, 4]); // returns Array [1, 8, 27, 64]
```
## See also
[multiply](multiply.md),
[square](square.md),
[pow](pow.md),
[cbrt](cbrt.md)

View File

@@ -0,0 +1,45 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function deepEqual
Test element wise whether two matrices are equal.
The function accepts both matrices and scalar values.
## Syntax
```js
math.deepEqual(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | First matrix to compare
`y` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Second matrix to compare
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Returns true when the input matrices have the same size and each of their elements is equal.
## Examples
```js
math.deepEqual(2, 4); // returns false
a = [2, 5, 1];
b = [2, 7, 1];
math.deepEqual(a, b); // returns false
math.equal(a, b); // returns [true, false, true]
```
## See also
[equal](equal.md),
[unequal](unequal.md)

View File

@@ -0,0 +1,55 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function derivative
Takes the derivative of an expression expressed in parser Nodes.
The derivative will be taken over the supplied variable in the
second parameter. If there are multiple variables in the expression,
it will return a partial derivative.
This uses rules of differentiation which can be found here:
- [Differentiation rules (Wikipedia)](http://en.wikipedia.org/wiki/Differentiation_rules)
## Syntax
```js
derivative(expr, variable)
derivative(expr, variable, options)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`expr` | Node &#124; string | The expression to differentiate
`variable` | SymbolNode &#124; string | The variable over which to differentiate
`options` | {simplify: boolean} | There is one option available, `simplify`, which is true by default. When false, output will not be simplified.
### Returns
Type | Description
---- | -----------
ConstantNode &#124; SymbolNode &#124; ParenthesisNode &#124; FunctionNode &#124; OperatorNode | The derivative of `expr`
## Examples
```js
math.derivative('x^2', 'x'); // Node {2 * x}
math.derivative('x^2', 'x', {simplify: false}); // Node {2 * 1 * x ^ (2 - 1)
math.derivative('sin(2x)', 'x')); // Node {2 * cos(2 * x)}
math.derivative('2*x', 'x').eval(); // number 2
math.derivative('x^2', 'x').eval({x: 4}); // number 8
var f = math.parse('x^2');
var x = math.parse('x');
math.derivative(f, x); // Node {2 * x}
```
## See also
[simplify](simplify.md),
[parse](parse.md),
[eval](eval.md)

View File

@@ -0,0 +1,43 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function det
Calculate the determinant of a matrix.
## Syntax
```js
math.det(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | Array &#124; Matrix | A matrix
### Returns
Type | Description
---- | -----------
number | The determinant of `x`
## Examples
```js
math.det([[1, 2], [3, 4]]); // returns -2
var A = [
[-2, 2, 3],
[-1, 1, 3],
[2, 0, -1]
]
math.det(A); // returns 6
```
## See also
[inv](inv.md)

View File

@@ -0,0 +1,55 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function diag
Create a diagonal matrix or retrieve the diagonal of a matrix
When `x` is a vector, a matrix with vector `x` on the diagonal will be returned.
When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector.
When k is positive, the values are placed on the super diagonal.
When k is negative, the values are placed on the sub diagonal.
## Syntax
```js
math.diag(X)
math.diag(X, format)
math.diag(X, k)
math.diag(X, k, format)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | Matrix &#124; Array | A two dimensional matrix or a vector
`k` | number &#124; BigNumber | The diagonal where the vector will be filled in or retrieved. Default value: 0.
`format` | string | The matrix storage format. Default value: 'dense'.
### Returns
Type | Description
---- | -----------
Matrix &#124; Array | Diagonal matrix from input vector, or diagonal from input matrix.
## Examples
```js
// create a diagonal matrix
math.diag([1, 2, 3]); // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
math.diag([1, 2, 3], 1); // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
math.diag([1, 2, 3], -1); // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]]
// retrieve the diagonal from a matrix
var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
math.diag(a); // returns [1, 5, 9]
```
## See also
[ones](ones.md),
[zeros](zeros.md),
[eye](eye.md)

View File

@@ -0,0 +1,72 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function distance
Calculates:
The eucledian distance between two points in 2 and 3 dimensional spaces.
Distance between point and a line in 2 and 3 dimensional spaces.
Pairwise distance between a set of 2D or 3D points
NOTE:
When substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c
For parametric equation of a 3D line, x0, y0, z0, a, b, c are from: (xx0, yy0, zz0) = t(a, b, c)
## Syntax
```js
math.distance([x1, y1], [x2, y2])
math.distance({pointOneX: 4, pointOneY: 5}, {pointTwoX: 2, pointTwoY: 7})
math.distance([x1, y1, z1], [x2, y2, z2])
math.distance({pointOneX: 4, pointOneY: 5, pointOneZ: 8}, {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9})
math.distance([[A], [B], [C]...])
math.distance([x1, y1], [LinePtX1, LinePtY1], [LinePtX2, LinePtY2])
math.distance({pointX: 1, pointY: 4}, {lineOnePtX: 6, lineOnePtY: 3}, {lineTwoPtX: 2, lineTwoPtY: 8})
math.distance([x1, y1, z1], [LinePtX1, LinePtY1, LinePtZ1], [LinePtX2, LinePtY2, LinePtZ2])
math.distance({pointX: 1, pointY: 4, pointZ: 7}, {lineOnePtX: 6, lineOnePtY: 3, lineOnePtZ: 4}, {lineTwoPtX: 2, lineTwoPtY: 8, lineTwoPtZ: 5})
math.distance([x1, y1], [xCoeffLine, yCoeffLine, constant])
math.distance({pointX: 10, pointY: 10}, {xCoeffLine: 8, yCoeffLine: 1, constant: 3})
math.distance([x1, y1, z1], [x0, y0, z0, a-tCoeff, b-tCoeff, c-tCoeff]) point and parametric equation of 3D line
math.distance([x, y, z], [x0, y0, z0, a, b, c])
math.distance({pointX: 2, pointY: 5, pointZ: 9}, {x0: 4, y0: 6, z0: 3, a: 4, b: 2, c: 0})
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | Array &#124; Matrix &#124; Object | Co-ordinates of first point
`y` | Array &#124; Matrix &#124; Object | Co-ordinates of second point
### Returns
Type | Description
---- | -----------
Number &#124; BigNumber | Returns the distance from two/three points
## Examples
```js
math.distance([0,0], [4,4]) // Returns 5.6569
math.distance(
{pointOneX: 0, pointOneY: 0},
{pointTwoX: 10, pointTwoY: 10}) // Returns 14.142135623730951
math.distance([1, 0, 1], [4, -2, 2]) // Returns 3.74166
math.distance(
{pointOneX: 4, pointOneY: 5, pointOneZ: 8},
{pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9}) // Returns 3
math.distance([[1, 2], [1, 2], [1, 3]]) // Returns [0, 1, 1]
math.distance([[1,2,4], [1,2,6], [8,1,3]]) // Returns [2, 7.14142842854285, 7.681145747868608]
math.distance([10, 10], [8, 1, 3]) // Returns 11.535230316796387
math.distance([10, 10], [2, 3], [-8, 0]) // Returns 8.759953130362847
math.distance(
{pointX: 1, pointY: 4},
{lineOnePtX: 6, lineOnePtY: 3},
{lineTwoPtX: 2, lineTwoPtY: 8}) // Returns 2.720549372624744
math.distance([2, 3, 1], [1, 1, 2, 5, 0, 1]) // Returns 2.3204774044612857
math.distance(
{pointX: 2, pointY: 3, pointZ: 1},
{x0: 1, y0: 1, z0: 2, a: 5, b: 0, c: 1} // Returns 2.3204774044612857
```

View File

@@ -0,0 +1,49 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function divide
Divide two values, `x / y`.
To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`.
## Syntax
```js
math.divide(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Numerator
`y` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Array &#124; Matrix | Denominator
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Quotient, `x / y`
## Examples
```js
math.divide(2, 3); // returns number 0.6666666666666666
var a = math.complex(5, 14);
var b = math.complex(4, 1);
math.divide(a, b); // returns Complex 2 + 3i
var c = [[7, -6], [13, -4]];
var d = [[1, 2], [4, 3]];
math.divide(c, d); // returns Array [[-9, 4], [-11, 6]]
var e = math.unit('18 km');
math.divide(e, 4.5); // returns Unit 4 km
```
## See also
[multiply](multiply.md)

View File

@@ -0,0 +1,42 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function dot
Calculate the dot product of two vectors. The dot product of
`A = [a1, a2, a3, ..., an]` and `B = [b1, b2, b3, ..., bn]` is defined as:
dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn
## Syntax
```js
math.dot(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | Array &#124; Matrix | First vector
`y` | Array &#124; Matrix | Second vector
### Returns
Type | Description
---- | -----------
number | Returns the dot product of `x` and `y`
## Examples
```js
math.dot([2, 4, 1], [2, 2, 3]); // returns number 15
math.multiply([2, 4, 1], [2, 2, 3]); // returns number 15
```
## See also
[multiply](multiply.md),
[cross](cross.md)

View File

@@ -0,0 +1,46 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function dotDivide
Divide two matrices element wise. The function accepts both matrices and
scalar values.
## Syntax
```js
math.dotDivide(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Numerator
`y` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Denominator
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Quotient, `x ./ y`
## Examples
```js
math.dotDivide(2, 4); // returns 0.5
a = [[9, 5], [6, 1]];
b = [[3, 2], [5, 2]];
math.dotDivide(a, b); // returns [[3, 2.5], [1.2, 0.5]]
math.divide(a, b); // returns [[1.75, 0.75], [-1.75, 2.25]]
```
## See also
[divide](divide.md),
[multiply](multiply.md),
[dotMultiply](dotMultiply.md)

View File

@@ -0,0 +1,46 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function dotMultiply
Multiply two matrices element wise. The function accepts both matrices and
scalar values.
## Syntax
```js
math.dotMultiply(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Left hand value
`y` | number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Right hand value
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Fraction &#124; Complex &#124; Unit &#124; Array &#124; Matrix | Multiplication of `x` and `y`
## Examples
```js
math.dotMultiply(2, 4); // returns 8
a = [[9, 5], [6, 1]];
b = [[3, 2], [5, 2]];
math.dotMultiply(a, b); // returns [[27, 10], [30, 2]]
math.multiply(a, b); // returns [[52, 28], [23, 14]]
```
## See also
[multiply](multiply.md),
[divide](divide.md),
[dotDivide](dotDivide.md)

View File

@@ -0,0 +1,43 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function dotPow
Calculates the power of x to y element wise.
## Syntax
```js
math.dotPow(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Complex &#124; Unit &#124; Array &#124; Matrix | The base
`y` | number &#124; BigNumber &#124; Complex &#124; Unit &#124; Array &#124; Matrix | The exponent
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Complex &#124; Unit &#124; Array &#124; Matrix | The value of `x` to the power `y`
## Examples
```js
math.dotPow(2, 3); // returns number 8
var a = [[1, 2], [4, 3]];
math.dotPow(a, 2); // returns Array [[1, 4], [16, 9]]
math.pow(a, 2); // returns Array [[9, 8], [16, 17]]
```
## See also
[pow](pow.md),
[sqrt](sqrt.md),
[multiply](multiply.md)

View File

@@ -0,0 +1,67 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function equal
Test whether two values are equal.
The function tests whether the relative difference between x and y is
smaller than the configured epsilon. The function cannot be used to
compare values smaller than approximately 2.22e-16.
For matrices, the function is evaluated element wise.
In case of complex numbers, x.re must equal y.re, and x.im must equal y.im.
Values `null` and `undefined` are compared strictly, thus `null` is only
equal to `null` and nothing else, and `undefined` is only equal to
`undefined` and nothing else.
## Syntax
```js
math.equal(x, y)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; boolean &#124; Complex &#124; Unit &#124; string &#124; Array &#124; Matrix | First value to compare
`y` | number &#124; BigNumber &#124; boolean &#124; Complex &#124; Unit &#124; string &#124; Array &#124; Matrix | Second value to compare
### Returns
Type | Description
---- | -----------
boolean &#124; Array &#124; Matrix | Returns true when the compared values are equal, else returns false
## Examples
```js
math.equal(2 + 2, 3); // returns false
math.equal(2 + 2, 4); // returns true
var a = math.unit('50 cm');
var b = math.unit('5 m');
math.equal(a, b); // returns true
var c = [2, 5, 1];
var d = [2, 7, 1];
math.equal(c, d); // returns [true, false, true]
math.deepEqual(c, d); // returns false
math.equal(0, null); // returns false
```
## See also
[unequal](unequal.md),
[smaller](smaller.md),
[smallerEq](smallerEq.md),
[larger](larger.md),
[largerEq](largerEq.md),
[compare](compare.md),
[deepEqual](deepEqual.md)

View File

@@ -0,0 +1,43 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function erf
Compute the erf function of a value using a rational Chebyshev
approximations for different intervals of x.
This is a translation of W. J. Cody's Fortran implementation from 1987
( http://www.netlib.org/specfun/erf ). See the AMS publication
"Rational Chebyshev Approximations for the Error Function" by W. J. Cody
for an explanation of this process.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.erf(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; Array &#124; Matrix | A real number
### Returns
Type | Description
---- | -----------
number &#124; Array &#124; Matrix | The erf of `x`
## Examples
```js
math.erf(0.2); // returns 0.22270258921047847
math.erf(-0.5); // returns -0.5204998778130465
math.erf(4); // returns 0.9999999845827421
```

View File

@@ -0,0 +1,47 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function eval
Evaluate an expression.
## Syntax
```js
math.eval(expr)
math.eval(expr, scope)
math.eval([expr1, expr2, expr3, ...])
math.eval([expr1, expr2, expr3, ...], scope)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`expr` | string &#124; string[] &#124; Matrix | The expression to be evaluated
`scope` | Object | Scope to read/write variables
### Returns
Type | Description
---- | -----------
* | The result of the expression
## Examples
```js
math.eval('(2+3)/4'); // 1.25
math.eval('sqrt(3^2 + 4^2)'); // 5
math.eval('sqrt(-4)'); // 2i
math.eval(['a=3', 'b=4', 'a*b']);, // [3, 4, 12]
var scope = {a:3, b:4};
math.eval('a * b', scope); // 12
```
## See also
[parse](parse.md),
[compile](compile.md)

View File

@@ -0,0 +1,47 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function exp
Calculate the exponent of a value.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.exp(x)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | A number or matrix to exponentiate
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Complex &#124; Array &#124; Matrix | Exponent of `x`
## Examples
```js
math.exp(2); // returns number 7.3890560989306495
math.pow(math.e, 2); // returns number 7.3890560989306495
math.log(math.exp(2)); // returns number 2
math.exp([1, 2, 3]);
// returns Array [
// 2.718281828459045,
// 7.3890560989306495,
// 20.085536923187668
// ]
```
## See also
[log](log.md),
[pow](pow.md)

View File

@@ -0,0 +1,51 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function eye
Create a 2-dimensional identity matrix with size m x n or n x n.
The matrix has ones on the diagonal and zeros elsewhere.
## Syntax
```js
math.eye(n)
math.eye(n, format)
math.eye(m, n)
math.eye(m, n, format)
math.eye([m, n])
math.eye([m, n], format)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`size` | ...number &#124; Matrix &#124; Array | The size for the matrix
`format` | string | The Matrix storage format
### Returns
Type | Description
---- | -----------
Matrix &#124; Array &#124; number | A matrix with ones on the diagonal.
## Examples
```js
math.eye(3); // returns [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
math.eye(3, 2); // returns [[1, 0], [0, 1], [0, 0]]
var A = [[1, 2, 3], [4, 5, 6]];
math.eye(math.size(A)); // returns [[1, 0, 0], [0, 1, 0]]
```
## See also
[diag](diag.md),
[ones](ones.md),
[zeros](zeros.md),
[size](size.md),
[range](range.md)

View File

@@ -0,0 +1,42 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function factorial
Compute the factorial of a value
Factorial only supports an integer value as argument.
For matrices, the function is evaluated element wise.
## Syntax
```js
math.factorial(n)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`n` | number &#124; BigNumber &#124; Array &#124; Matrix | An integer number
### Returns
Type | Description
---- | -----------
number &#124; BigNumber &#124; Array &#124; Matrix | The factorial of `n`
## Examples
```js
math.factorial(5); // returns 120
math.factorial(3); // returns 6
```
## See also
[combinations](combinations.md),
[gamma](gamma.md),
[permutations](permutations.md)

View File

@@ -0,0 +1,44 @@
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
# Function filter
Filter the items in an array or one dimensional matrix.
## Syntax
```js
math.filter(x, test)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
`x` | Matrix &#124; Array | A one dimensional matrix or array to filter
`test` | Function &#124; RegExp | A function or regular expression to test items. All entries for which `test` returns true are returned. When `test` is a function, it is invoked with three parameters: the value of the element, the index of the element, and the matrix/array being traversed. The function must return a boolean.
### Returns
Type | Description
---- | -----------
Matrix &#124; Array | Returns the filtered matrix.
## Examples
```js
function isPositive (x) {
return x > 0;
}
math.filter([6, -2, -1, 4, 3], isPositive); // returns [6, 4, 3]
math.filter(["23", "foo", "100", "55", "bar"], /[0-9]+/); // returns ["23", "100", "55"]
```
## See also
[forEach](forEach.md),
[map](map.md),
[sort](sort.md)

Some files were not shown because too many files have changed in this diff Show More