### Start Development Mode with npm Source: https://github.com/josdejong/mathjs/blob/develop/examples/code_editor/README.md Use this command to start the development server and begin working on the project. ```bash npm run dev ``` -------------------------------- ### Install and Build Math.js Source: https://github.com/josdejong/mathjs/blob/develop/test/benchmark/README.md Run these commands to install dependencies and build the math.js project before running benchmarks. ```bash $ npm install $ npm run build ``` -------------------------------- ### Installation and Loading Source: https://context7.com/josdejong/mathjs/llms.txt Instructions on how to install and import Math.js in different JavaScript environments like Node.js (CommonJS and ESM) and browsers. ```APIDOC ## Installation and Loading Install and import math.js in Node.js or bundler environments. ```js // Install // npm install mathjs // ESM: import specific functions (tree-shaking friendly) import { sqrt, add, evaluate, chain, pi, e } from 'mathjs' console.log(sqrt(-4).toString()) // '2i' console.log(add(1, 2)) // 3 console.log(evaluate('12 / (2.3 + 0.7)')) // 4 // ESM: create a configurable instance import { create, all } from 'mathjs' const math = create(all, { number: 'BigNumber', precision: 64 }) console.log(math.evaluate('0.1 + 0.2').toString()) // '0.3' // CommonJS (Node.js) const { sqrt, evaluate } = require('mathjs') console.log(sqrt(16)) // 4 // Browser (via CDN / script tag) // // math.sqrt(-4).toString() => '2i' // Lightweight number-only build (no BigNumbers, Complex, etc.) import { sqrt, add } from 'mathjs/number' console.log(sqrt(4)) // 2 console.log(sqrt(-4)) // NaN (no complex number support) ``` ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/josdejong/mathjs/blob/develop/README.md Install all necessary dependencies for the math.js project after cloning. This command should be executed within the project's root directory. ```bash npm install ``` -------------------------------- ### Install and Import Math.js (ESM) Source: https://context7.com/josdejong/mathjs/llms.txt Install math.js using npm. Import specific functions for tree-shaking or create a configurable instance with custom settings. ```javascript // Install // npm install mathjs // ESM: import specific functions (tree-shaking friendly) import { sqrt, add, evaluate, chain, pi, e } from 'mathjs' console.log(sqrt(-4).toString()) // '2i' console.log(add(1, 2)) // 3 console.log(evaluate('12 / (2.3 + 0.7)')) // 4 // ESM: create a configurable instance import { create, all } from 'mathjs' const math = create(all, { number: 'BigNumber', precision: 64 }) console.log(math.evaluate('0.1 + 0.2').toString()) // '0.3' ``` ```javascript // CommonJS (Node.js) const { sqrt, evaluate } = require('mathjs') console.log(sqrt(16)) // 4 ``` ```javascript // Browser (via CDN / script tag) // // math.sqrt(-4).toString() => '2i' ``` ```javascript // Lightweight number-only build (no BigNumbers, Complex, etc.) import { sqrt, add } from 'mathjs/number' console.log(sqrt(4)) // 2 console.log(sqrt(-4)) // NaN (no complex number support) ``` -------------------------------- ### Basic Chaining Example Source: https://github.com/josdejong/mathjs/blob/develop/docs/core/chaining.md Demonstrates chaining arithmetic operations like add and subtract. Use `done()` to get the final result. ```javascript math.chain(3) .add(4) .subtract(2) .done() // 5 ``` -------------------------------- ### Install Math.js via npm Source: https://github.com/josdejong/mathjs/blob/develop/README.md Install the math.js library using npm. This command should be run in your project's root directory. ```bash npm install mathjs ``` -------------------------------- ### Range Examples Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/matrixrange.md Demonstrates creating ranges with default and custom steps, and converting them to arrays. ```javascript const c = new Range(2, 6) // 2:1:5 c.toArray() // [2, 3, 4, 5] const d = new Range(2, -3, -1) // 2:-1:-2 d.toArray() // [2, 1, 0, -1, -2] ``` -------------------------------- ### Install Math.js Globally Source: https://github.com/josdejong/mathjs/blob/develop/docs/command_line_interface.md Install the math.js library globally on your system using npm. This command may require administrator privileges. ```bash npm install -g mathjs ``` -------------------------------- ### Code Editor Example with CodeMirror and KaTeX Source: https://github.com/josdejong/mathjs/blob/develop/HISTORY.md A fully featured code editor example integrating CodeMirror for editing and KaTeX for rendering mathematical expressions. ```html
``` -------------------------------- ### Pass Functions as Parameters Source: https://github.com/josdejong/mathjs/blob/develop/docs/expressions/syntax.md Demonstrates passing functions as arguments to other functions, including a simplistic numerical derivative example. ```javascript const parser = math.parser() parser.evaluate('twice(func, x) = func(func(x))') parser.evaluate('twice(square, 2)') // 16 parser.evaluate('f(x) = 3*x') parser.evaluate('twice(f, 2)') // 18 // a simplistic "numerical derivative": parser.evaluate('eps = 1e-10') parser.evaluate('nd(f, x) = (f(x+eps) - func(x-eps))/(2*eps)') parser.evaluate('nd(square,2)') // 4.000000330961484 ``` -------------------------------- ### Custom Math.js Instance with Specific Functions Source: https://github.com/josdejong/mathjs/blob/develop/docs/custom_bundling.md Create a Math.js instance with only the necessary functions and their dependencies to reduce bundle size. This example loads `fraction`, `add`, `divide`, and `format`. ```javascript // file: custom_loading.js import { create, fractionDependencies, addDependencies, divideDependencies, formatDependencies } from 'mathjs' const config = { // optionally, you can specify configuration } // Create just the functions we need const { fraction, add, divide, format } = create({ fractionDependencies, addDependencies, divideDependencies, formatDependencies }, config) // Use the created functions const a = fraction(1, 3) const b = fraction(3, 7) const c = add(a, b) const d = divide(a, b) console.log('c =', format(c)) // outputs "c = 16/21" console.log('d =', format(d)) // outputs "d = 7/9" ``` -------------------------------- ### Creating a Factory Function with Dependencies Source: https://github.com/josdejong/mathjs/blob/develop/docs/core/extension.md Example of creating a factory function named 'negativeSquare' that depends on 'multiply' and 'unaryMinus'. ```javascript import { factory, create, all } from 'mathjs' // create a factory function const name = 'negativeSquare' const dependencies = ['multiply', 'unaryMinus'] const createNegativeSquare = factory(name, dependencies, function ({ multiply, unaryMinus }) { return function negativeSquare (x) { return unaryMinus(multiply(x, x)) } }) // create an instance of the function yourself: const multiply = (a, b) => a * b const unaryMinus = (a) => -a const negativeSquare = createNegativeSquare({ multiply, unaryMinus }) console.log(negativeSquare(3)) // -9 // or import the factory in a mathjs instance and use it there const math = create(all) math.import(createNegativeSquare) console.log(math.negativeSquare(4)) // -16 console.log(math.evaluate('negativeSquare(5)')) // -25 ``` -------------------------------- ### Create and Use a Parser Instance Source: https://github.com/josdejong/mathjs/blob/develop/docs/expressions/parsing.md Instantiate a parser using `math.parser()` to manage scope and evaluate expressions. The parser allows setting, getting, and removing variables and functions. ```javascript const parser = math.parser() ``` -------------------------------- ### Migrate Matrix Indexing to v15 Source: https://github.com/josdejong/mathjs/blob/develop/docs/expressions/syntax.md Examples demonstrating the conversion of v14 matrix indexing to the v15 equivalent, particularly when scalar indices need to be wrapped in array brackets to preserve dimensions. ```javascript parser = math.parser() parser.evaluate('m = [1, 2, 3; 4, 5, 6]') ``` ```javascript m[2, 2:3] // v14: [[5, 6]] m[[2], 2:3] // v15: [[5, 6]] ``` ```javascript m[1:2, 3] // v14: [[3], [6]] m[1:2, [3]] // v15: [[3], [6]] ``` -------------------------------- ### Clone Math.js Repository Source: https://github.com/josdejong/mathjs/blob/develop/README.md Clone the math.js project from GitHub to your local machine. Navigate into the cloned directory to proceed with installation and building. ```bash git clone git@github.com:josdejong/mathjs.git cd mathjs ``` -------------------------------- ### Run Single Benchmark Set Source: https://github.com/josdejong/mathjs/blob/develop/test/benchmark/README.md Use this command to run a specific set of benchmarks, for example, the expression parser benchmarks. ```bash $ node expression_parser.js ``` -------------------------------- ### Bundle Custom Math.js Loading with Webpack Source: https://github.com/josdejong/mathjs/blob/develop/docs/custom_bundling.md Example command to bundle a custom Math.js loading script using Webpack in production mode. This leverages tree-shaking to include only the used parts of the library. ```bash npx webpack custom_loading.js -o custom_loading.bundle.js --mode=production ``` -------------------------------- ### index.toString Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/matrixindex.md Gets the string representation of the index, for example '[2:6]' or '[0:2:10, 4:7, [1,2,3]]'. ```APIDOC ## index.toString() ### Description Get the string representation of the index, for example '[2:6]' or '[0:2:10, 4:7, [1,2,3]]' ### Returns - **String** - str ``` -------------------------------- ### Create and Configure Math.js Instance Source: https://github.com/josdejong/mathjs/blob/develop/docs/core/configuration.md Demonstrates how to create a Math.js instance with custom configuration options and how to read and change these settings after creation. Use this to set initial parameters like precision, number types, and matrix handling. ```javascript import { create, all } from 'mathjs' // create a mathjs instance with configuration const config = { relTol: 1e-12, absTol: 1e-15, matrix: 'Matrix', number: 'number', numberFallback: 'number', precision: 64, predictable: false, randomSeed: null, legacySubset: false } const math = create(all, config) // read the applied configuration console.log(math.config()) // change the configuration math.config({ number: 'BigNumber' }) ``` -------------------------------- ### range.format([options]) Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/matrixrange.md Gets a string representation of the range, with optional formatting options. Output is formatted as 'start:step:end'. ```APIDOC ## range.format([options]) ### Description 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' ### Returns - **string** - str ### Parameters #### Path Parameters - **[options]** (Object | number | function) - Formatting options. See lib/utils/number:format for a description of the available options. ``` -------------------------------- ### Matrix Indexing Migration Examples Source: https://github.com/josdejong/mathjs/blob/develop/docs/datatypes/matrices.md Illustrates the changes in matrix indexing behavior between math.js v14 and v15. Scalar indices need to be wrapped in array brackets to maintain array output. ```javascript const m = math.matrix([[1, 2, 3], [4, 5, 6]]) ``` ```javascript math.subset(m, math.index([0, 1], [1, 2])) ``` ```javascript math.subset(m, math.index(1, [1, 2])) ``` ```javascript math.subset(m, math.index([0, 1], 2)) ``` ```javascript math.subset(m, math.index(1, 2)) ``` -------------------------------- ### Math.js REPL Debugging Source: https://github.com/josdejong/mathjs/blob/develop/docs/command_line_interface.md Start the Math.js REPL (Read-Evaluate-Print Loop) using `bin/repl.js` for command-line debugging within a Node.js environment. Exit using 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' } ] } > ``` -------------------------------- ### Math.js v5 vs v6: Global config and import Source: https://github.com/josdejong/mathjs/blob/develop/HISTORY.md Illustrates the change in how configuration and imports are handled, moving from global context in v5 to instance-based in v6. ```javascript // v5 import * as mathjs from 'mathjs' mathjs.config(...) // error in v6.0.0 mathjs.import(...) // error in v6.0.0 ``` ```javascript // v6 import { create, all } from 'mathjs' const config = { number: 'BigNumber' } const mathjs = create(all, config) mathjs.import(...) ``` -------------------------------- ### Build and Test math.js Source: https://github.com/josdejong/mathjs/blob/develop/misc/how_to_publish.md Run this command to build the distribution files and execute tests. Verify the created files for correct date and version. ```bash npm run build-and-test ``` -------------------------------- ### Initialize Simulation Context and Constants Source: https://github.com/josdejong/mathjs/blob/develop/examples/browser/rocket_trajectory_optimization.html Sets up a Math.js parser context and defines physical constants and initial conditions for the rocket trajectory simulation. ```javascript // Create a math.js context for our simulation. Everything else occurs in the context of the expression parser! const sim = math.parser() sim.evaluate("G = 6.67408e-11 m^3 kg^-1 s^-2") // Gravitational constant sim.evaluate("mbody = 5.9724e24 kg") // Mass of Earth sim.evaluate("mu = G * mbody") // Standard gravitational parameter sim.evaluate("g0 = 9.80665 m/s^2") // Standard gravity: used for calculating prop consumption (dmdt) sim.evaluate("r0 = 6371 km") // Mean radius of Earth sim.evaluate("t0 = 0 s") // Simulation start sim.evaluate("dt = 0.5 s") // Simulation timestep sim.evaluate("tfinal = 149.5 s") // Simulation duration sim.evaluate("isp_sea = 282 s") // Specific impulse (at sea level) sim.evaluate("isp_vac = 311 s") // Specific impulse (in vacuum) sim.evaluate("gamma0 = 89.99970 deg") // Initial pitch angle (90 deg is vertical) sim.evaluate("v0 = 1 m/s") // Initial velocity (must be non-zero because ODE is ill-conditioned) sim.evaluate("phi0 = 0 deg") // Initial orbital reference angle sim.evaluate("m1 = 433100 kg") // First stage mass sim.evaluate("m2 = 111500 kg") // Second stage mass sim.evaluate("m3 = 1700 kg") // Third stage / fairing mass sim.evaluate("mp = 5000 kg") // Payload mass sim.evaluate("m0 = m1+m2+m3+mp") // Initial mass of rocket sim.evaluate("dm = 2750 kg/s") // Mass flow rate sim.evaluate("A = (3.66 m)^2 * pi") // Area of the rocket sim.evaluate("dragCoef = 0.2") // Drag coefficient ``` -------------------------------- ### Execute Math.js Expressions in CLI Source: https://github.com/josdejong/mathjs/blob/develop/docs/command_line_interface.md Use the mathjs command to open an interactive prompt and evaluate mathematical expressions. Examples include basic arithmetic, unit conversions, trigonometric functions, complex numbers, and matrix determinants. ```bash mathjs > 12 / (2.3 + 0.7) 4 ``` ```bash > 12.7 cm to inch 5 inch ``` ```bash > sin(45 deg) ^ 2 0.5 ``` ```bash > 9 / 3 + 2i 3 + 2i ``` ```bash > det([-1, 2; 3, 1]) -7 ``` -------------------------------- ### Create Ranges Source: https://github.com/josdejong/mathjs/blob/develop/docs/datatypes/matrices.md The `range` function generates a sequence of numbers. It takes a start and end value, and an optional step. The start is inclusive, and the end is exclusive. ```javascript 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] ``` -------------------------------- ### Create Full Math.js Instance Source: https://github.com/josdejong/mathjs/blob/develop/docs/custom_bundling.md Use the `create` function with `all` to initialize a Math.js instance containing all available functionality. ```javascript import { create, all } from 'mathjs' const math = create(all) ``` -------------------------------- ### Math.js v6: Loading specific functions with custom configuration Source: https://github.com/josdejong/mathjs/blob/develop/HISTORY.md Demonstrates how to load specific functions with custom configuration in Math.js v6 using the `create` function. ```javascript import { create, addDependencies, multiplyDependencies } from 'mathjs' const config = { number: 'BigNumber' } const math = create({ addDependencies, multiplyDependencies }, config) ``` -------------------------------- ### Create Math.js Instance with Custom Configuration Source: https://context7.com/josdejong/mathjs/llms.txt Create a new math.js instance by wiring together factory functions. Use `all` for a full library or pass specific dependencies for a minimal, tree-shakeable bundle. ```javascript import { create, all, addDependencies, multiplyDependencies, fractionDependencies, formatDependencies } from 'mathjs' // Full instance with custom configuration const math = create(all, { number: 'BigNumber', precision: 32, matrix: 'Array' }) console.log(math.evaluate('1/3').toString()) // '0.33333333333333333333333333333333' ``` ```javascript // Minimal instance with only the needed functions (tree-shakeable) const { add, multiply, fraction, format } = create({ addDependencies, multiplyDependencies, fractionDependencies, formatDependencies }) const a = fraction(1, 3) const b = fraction(1, 6) console.log(format(add(a, b))) // '1/2' console.log(format(multiply(a, b))) // '1/18' ``` -------------------------------- ### Manage Parser Scope with Get, Set, and Remove Source: https://github.com/josdejong/mathjs/blob/develop/docs/expressions/parsing.md Interact with the parser's scope using `get`, `set`, and `remove` methods to retrieve, define, or delete variables and functions. ```javascript // get and set variables and functions const x = parser.get('x') // x = 3.5 const f = parser.get('f') // function const g = f(3, 3) // g = 27 parser.set('h', 500) parser.evaluate('h / 2') // 250 parser.set('hello', function (name) { return 'hello, ' + name + '!' }) parser.evaluate('hello("user")') // "hello, user!" ``` -------------------------------- ### Create Math.js Instance with Specific Functions Source: https://github.com/josdejong/mathjs/blob/develop/README.md Demonstrates how to create a Math.js instance by loading only the factory functions for a specific function like 'add'. This allows for a more lightweight build by excluding unnecessary functionality. ```javascript import { addDependencies } from 'mathjs/lib/es/dependencies.js'; const math = mathjs.create(addDependencies); console.log(math.add(2, 3)); // 5 ``` -------------------------------- ### new Range(start, end, [step]) Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/matrixrange.md Creates a new Range object. A range has a start, step, and end, and contains functions to iterate over the range. The step parameter is optional and defaults to 1. ```APIDOC ## new Range(start, end, [step]) ### Description 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 const range = new Range(start, end) const 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 const c = new Range(2, 6) // 2:1:5 c.toArray() // [2, 3, 4, 5] const d = new Range(2, -3, -1) // 2:-1:-2 d.toArray() // [2, 1, 0, -1, -2] ``` ### Parameters #### Path Parameters - **start** (number) - included lower bound - **end** (number) - excluded upper bound - **[step]** (number) - step size, default value is 1 ``` -------------------------------- ### index.toJSON Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/matrixindex.md Gets a JSON representation of the Index. ```APIDOC ## index.toJSON() ### Description Get a JSON representation of the Index ### Returns - **Object** - Returns a JSON object structured as: `{"mathjs": "Index", "ranges": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}` ``` -------------------------------- ### Unit Constructor and Parsing Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/unit.md Demonstrates how to create Unit instances using the constructor with a value and name, or by parsing a string representation. ```APIDOC ## new Unit([value], [name]) A unit can be constructed in the following ways: ```js const a = new Unit(value, name) const b = new Unit(null, name) const c = Unit.parse(str) ``` Example usage: ```js const a = new Unit(5, 'cm') // 50 mm const b = Unit.parse('23 kg') // 23 kg const c = math.in(a, new Unit(null, 'm') // 0.05 m const d = new Unit(9.81, "m/s^2") // 9.81 m/s^2 ``` ### Parameters #### value - **Type**:number | BigNumber | Fraction | Complex | boolean
- **Description**: A value like 5.2
#### name
- **Type**: string
- **Description**: 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.
```
--------------------------------
### range.toString()
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/matrixrange.md
Gets a string representation of the range.
```APIDOC
## range.toString()
### Description
Get a string representation of the range.
```
--------------------------------
### Math.js Instance Creation (Old vs New)
Source: https://github.com/josdejong/mathjs/blob/develop/HISTORY.md
Illustrates the older method of creating a math.js instance versus the simplified new method.
```javascript
// instead of:
var mathjs = require('mathjs'), // load math.js
math = mathjs(); // create an instance
// just do:
var math = require('mathjs');
```
--------------------------------
### SparseMatrix.size()
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/sparsematrix.md
Get the dimensions (size) of the matrix as an array of numbers.
```APIDOC
## sparseMatrix.size()
### Description
Get the dimensions (size) of the matrix.
### Returns
* `ArrayDenseMatrix
### Returns
Object - A JSON object representing the matrix.
```
--------------------------------
### Use Methods on Units
Source: https://github.com/josdejong/mathjs/blob/develop/docs/expressions/syntax.md
Example of using a method on a unit object within the parser to convert units.
```javascript
const parser = math.parser()
parser.evaluate('a = 1 m') // Unit 1 m
parser.evaluate('a.toNumber("mm")') // 1000
```
--------------------------------
### Initialize Matrices with Functions
Source: https://github.com/josdejong/mathjs/blob/develop/docs/expressions/syntax.md
Use functions like zeros, ones, identity, and range to initialize matrices with specific values or patterns.
```javascript
math.evaluate('zeros(3, 2)') // Matrix, [[0, 0], [0, 0], [0, 0]], size [3, 2]
math.evaluate('ones(3)') // Matrix, [1, 1, 1], size [3]
math.evaluate('5 * ones(2, 2)') // Matrix, [[5, 5], [5, 5]], size [2, 2]
// create an identity matrix
math.evaluate('identity(2)') // Matrix, [[1, 0], [0, 1]], size [2, 2]
// create a range
math.evaluate('1:4') // Matrix, [1, 2, 3, 4], size [4]
math.evaluate('0:2:10') // Matrix, [0, 2, 4, 6, 8, 10], size [6]
```
--------------------------------
### Unit Conversion and Best Unit Selection
Source: https://github.com/josdejong/mathjs/blob/develop/test/unit-tests/test.html
Shows how to create and convert units using Math.js. Demonstrates converting meters to various smaller units and selecting the best unit for a given value.
```javascript
print(math.unit('0.01m').toString());
print(math.unit('1m').toString());
print(math.unit('10m').toString());
print(math.unit('100m').toString());
print(math.unit('500m').toString());
print(math.unit('800m').toString());
print(math.unit('1000m').toString());
print(math.unit('1100m').toString());
```
```javascript
print(math.unit('5cm').toBest(['km', 'm', 'cm', 'mm', 'um', 'nm']).toString());
```
```javascript
print("math.unit(10, 'm').toBest(['mm', 'km'], { offset: 1.5 }) => ", math.unit(10, 'm').toBest(['mm', 'km'], { offset: 1.5 }));
```
```javascript
print("math.unit(10, 'm').toBest(['cm', 'km'], { offset: 0.5 }) => ", math.unit(10, 'm').toBest(['cm', 'km'], { offset: 0.5 }));
```
```javascript
print("math.unit(10, 'm').toBest(['nm', 'km'], { offset: 1.5 }) => ", math.unit(10, 'm').toBest(['nm', 'km'], { offset: 1.5 }));
```
```javascript
print("math.unit(10, 'm').toBest(['um', 'nm'], { offset: 1.5 }) => ", math.unit(10, 'm').toBest(['um', 'nm'], { offset: 1.5 }));
```
```javascript
print("math.unit(10, 'm').toBest(['Mm', 'km'], { offset: 1.5 }) => ", math.unit(10, 'm').toBest(['Mm', 'km'], { offset: 1.5 }));
```
```javascript
print("math.unit(10, 'm').toBest(['Gm', 'km'], { offset: 1.5 }) => ", math.unit(10, 'm').toBest(['Gm', 'km'], { offset: 1.5 }));
```
```javascript
print("math.unit(2 / 3, 'cm').toBest() => ", math.unit(2 / 3, 'cm').toBest());
```
--------------------------------
### index.toArray
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/matrixindex.md
Expands the Index into an array. For example, new Index([0,3], [2,7]) returns [[0,1,2], [2,3,4,5,6]].
```APIDOC
## index.toArray()
### Description
Expand the Index into an array.
For example new Index([0,3], [2,7]) returns [[0,1,2], [2,3,4,5,6]]
### Returns
- **Array** - array
```
--------------------------------
### math.create(factories, config)
Source: https://context7.com/josdejong/mathjs/llms.txt
Creates a new configurable math.js instance by wiring together provided factory functions. Allows for custom configurations and building minimal bundles.
```APIDOC
## math.create(factories, config)
Creates a new configurable mathjs instance by wiring together the provided factory functions. Use `all` for the complete library, or pass specific `*Dependencies` objects to build a minimal bundle.
```js
import {
create,
all,
addDependencies,
multiplyDependencies,
fractionDependencies,
formatDependencies
} from 'mathjs'
// Full instance with custom configuration
const math = create(all, {
number: 'BigNumber',
precision: 32,
matrix: 'Array'
})
console.log(math.evaluate('1/3').toString()) // '0.33333333333333333333333333333333'
// Minimal instance with only the needed functions (tree-shakeable)
const { add, multiply, fraction, format } = create({
addDependencies,
multiplyDependencies,
fractionDependencies,
formatDependencies
})
const a = fraction(1, 3)
const b = fraction(1, 6)
console.log(format(add(a, b))) // '1/2'
console.log(format(multiply(a, b))) // '1/18'
```
```
--------------------------------
### unit.formatUnits()
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/unit.md
Gets a string representation of the units of this Unit, without the value. This is useful for displaying only the unit symbol.
```APIDOC
## unit.formatUnits()
### Description
Get a string representation of the units of this Unit, without the value.
### Method
instance method of Unit
### Returns
`string` - A string representation of the unit symbols.
```
--------------------------------
### Get Single Element from SparseMatrix
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/sparsematrix.md
Retrieve the value of a single element from the SparseMatrix at a specified zero-based index.
```javascript
const element = matrix.get([row, col])
```
--------------------------------
### Create a New Math.js Instance
Source: https://github.com/josdejong/mathjs/blob/develop/HISTORY.md
Use `math.create([options])` to create a new instance of math.js, especially when you need to configure options or avoid side effects.
```javascript
var math = require('mathjs');
var instance = math.create();
```
--------------------------------
### Get String Representation of Index
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/matrixindex.md
Returns a string representation of the index, such as '[2:6]' or '[0:2:10, 4:7, [1,2,3]]'.
```javascript
const str = index.toString()
```
--------------------------------
### Unit Instance Methods
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/unit.md
Provides an overview of the methods available on Unit instances for operations like cloning, checking properties, and performing calculations.
```APIDOC
## Unit Instance Methods
### .valueOf()
Returns the string representation of the unit.
**Kind**: instance property of Unit
### .clone()
create a copy of this unit
**Kind**: instance method of Unit
**Returns**: Unit - Returns a cloned version of the unit
### ._isDerived()
Return whether the unit is derived (such as m/s, or cm^2, but not N)
**Kind**: instance method of Unit
**Returns**: boolean - True if the unit is derived
### .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 Unit
#### Parameters
- **base**: BASE_UNITS | STRING | undefined
### .equalBase(other)
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 Unit
**Returns**: boolean - true if equal base
#### Parameters
- **other**: Unit
### .equals(other)
Check if this unit equals another unit
**Kind**: instance method of Unit
**Returns**: boolean - true if both units are equal
#### Parameters
- **other**: Unit
### .multiply(other)
Multiply this unit with another one
**Kind**: instance method of Unit
**Returns**: Unit - product of this unit and the other unit
#### Parameters
- **other**: Unit
### .divide(other)
Divide this unit by another one
**Kind**: instance method of Unit
**Returns**: Unit - result of dividing this unit by the other unit
#### Parameters
- **other**: Unit
### .pow(p)
Calculate the power of a unit
**Kind**: instance method of Unit
**Returns**: Unit - The result: this^p
#### Parameters
- **p**: number | Fraction | BigNumber
### .abs(x)
```
--------------------------------
### Convert Index to Array
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/matrixindex.md
Get the primitive value of the Index as a two-dimensional array. This is equivalent to calling Index.toArray().
```javascript
const array = index.valueOf
```
--------------------------------
### Define and Use Custom Functions
Source: https://github.com/josdejong/mathjs/blob/develop/docs/expressions/syntax.md
Shows how to define single-line custom functions with one or more variables and then evaluate them.
```javascript
const parser = math.parser()
parser.evaluate('f(x) = x ^ 2 - 5')
parser.evaluate('f(2)') // -1
parser.evaluate('f(3)') // 4
parser.evaluate('g(x, y) = x ^ y')
parser.evaluate('g(2, 3)') // 8
```
--------------------------------
### Create Math.js Instance and Import Functions
Source: https://github.com/josdejong/mathjs/blob/develop/docs/core/extension.md
Initialize a Math.js instance and import custom functions or variables. The `import` function accepts an object of functions/values or an array of factory functions.
```javascript
import { create, all } from 'mathjs'
const math = create(all)
math.import(/* ... */)
```
--------------------------------
### Matrix Multiplication
Source: https://github.com/josdejong/mathjs/blob/develop/docs/datatypes/matrices.md
Standard matrix multiplication can be performed using `math.multiply`. This example shows multiplying an array by a matrix.
```javascript
// multiply an array with a matrix
const c = [[2, 0], [-1, 3]] // Array
const d = math.matrix([[7, 1], [-2, 3]]) // Matrix
math.multiply(c, d) // Matrix, [[14, 2], [-13, 8]]
```
--------------------------------
### Split unit into parts
Source: https://github.com/josdejong/mathjs/blob/develop/docs/datatypes/units.md
Splits a unit into specified component units. This example splits a meter into feet and inches.
```javascript
const u = math.unit(1, 'm')
u.splitUnit(['ft', 'in']) // 3 feet,3.3700787401574765 inch
```
--------------------------------
### Object Creation
Source: https://github.com/josdejong/mathjs/blob/develop/docs/expressions/syntax.md
Demonstrates the syntax for creating objects using curly braces.
```javascript
{a: 1, b: 2}
```
--------------------------------
### unit.format([options])
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/unit.md
Gets a string representation of the Unit, with optional formatting options. Allows customization of how the unit is displayed.
```APIDOC
## unit.format([options])
### Description
Get a string representation of the Unit, with optional formatting options.
### Method
instance method of Unit
### Parameters
#### Path Parameters
- **[options]** (Object | number | function) - Formatting options. See lib/utils/number:format for a description of the available options.
```
--------------------------------
### Retrieve a Specific Dimension
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/matrixindex.md
Get the Range object for a specified dimension of the index. Returns null if the dimension does not exist.
```javascript
const range = index.dimension(dim)
```
--------------------------------
### Run Tests in Browser (Headless Mode)
Source: https://github.com/josdejong/mathjs/blob/develop/README.md
Command to execute the Math.js tests in a Firefox browser using headless mode.
```bash
npm run test:browser
```
--------------------------------
### Range.parse(str)
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/matrixrange.md
Parses a string into a Range object. The string should define the start, optional step, and end, separated by colons.
```APIDOC
## Range.parse(str)
### Description
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'.
### Parameters
#### Path Parameters
- **str** (string) - The string to parse into a range.
### Returns
`Range` | `null` - Returns the parsed Range object or null if the string is invalid.
```
--------------------------------
### Create Math.js instance with specific functions and custom config (ES Modules)
Source: https://github.com/josdejong/mathjs/blob/develop/HISTORY.md
Load only specific functions with custom configuration, useful for fine-grained control over the Math.js instance.
```javascript
import { create, addDependencies, multiplyDependencies } from 'mathjs'
const config = { number: 'BigNumber' }
const { add, multiply } = create({
addDependencies,
multiplyDependencies
}, config)
```
--------------------------------
### Create BigInts in math.js
Source: https://github.com/josdejong/mathjs/blob/develop/docs/datatypes/bigints.md
Demonstrates three ways to create BigInt values: using the 'n' suffix, the BigInt constructor, and the math.bigint utility function.
```javascript
42n
BigInt('42')
math.bigint('42')
```
--------------------------------
### Lazy Evaluation Example
Source: https://github.com/josdejong/mathjs/blob/develop/docs/expressions/syntax.md
Demonstrates lazy evaluation where the right-hand side of a logical AND operation is not evaluated if the left-hand side is false.
```javascript
math.evaluate('false and x') // false, no matter what x equals
```
--------------------------------
### Create and Convert Units
Source: https://github.com/josdejong/mathjs/blob/develop/docs/expressions/syntax.md
Demonstrates creating units and converting between different units using the 'to' or 'in' operators. Also shows converting a unit to a number by providing the target unit.
```javascript
math.evaluate('5.4 kg') // Unit, 5.4 kg
```
```javascript
math.evaluate('2 inch to cm') // Unit, 5.08 cm
```
```javascript
math.evaluate('20 celsius in fahrenheit') // Unit, ~68 fahrenheit
```
```javascript
math.evaluate('90 km/h to m/s') // Unit, 25 m / s
```
```javascript
math.evaluate('number(5 cm, mm)') // Number, 50
```
--------------------------------
### SparseMatrix.density()
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/sparsematrix.md
Get the matrix density, which is the ratio of non-zero elements to the total number of elements. Returns a number between 0 and 1.
```APIDOC
## sparseMatrix.density()
### Description
Get the matrix density.
### Returns
* `number`: The matrix density.
### Usage
```js
const density = matrix.density() // retrieve matrix density
```
```
--------------------------------
### Bitwise AND Operator
Source: https://github.com/josdejong/mathjs/blob/develop/docs/expressions/syntax.md
Demonstrates the bitwise AND operator.
```javascript
5 & 3
```
--------------------------------
### Get SparseMatrix Density
Source: https://github.com/josdejong/mathjs/blob/develop/docs/reference/classes/sparsematrix.md
Calculate and retrieve the density of the SparseMatrix. Density is the ratio of non-zero elements to the total number of elements.
```javascript
const density = matrix.density() // retrieve matrix density
```