or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

arithmetic.mddata-types.mdexpressions.mdindex.mdmatrices.mdprobability.mdstatistics.mdtrigonometry.mdunits.md

index.mddocs/

0

# Math.js

1

2

Math.js 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.

3

4

## Package Information

5

6

```bash

7

npm install mathjs

8

```

9

10

- **Package**: `mathjs`

11

- **Version**: 14.6.0+

12

- **License**: Apache-2.0

13

- **Repository**: [josdejong/mathjs](https://github.com/josdejong/mathjs)

14

- **Documentation**: [mathjs.org](https://mathjs.org)

15

16

## Core Imports

17

18

Math.js supports multiple import patterns depending on your needs:

19

20

### Full Import (All Functions)

21

```typescript

22

import { create, all } from 'mathjs'

23

const math = create(all)

24

25

// Or with CommonJS

26

const { create, all } = require('mathjs')

27

const math = create(all)

28

```

29

30

### Selective Imports (Tree-shakeable)

31

```typescript

32

import {

33

create,

34

addDependencies,

35

subtractDependencies,

36

multiplyDependencies,

37

evaluateDependencies

38

} from 'mathjs'

39

40

const math = create({

41

addDependencies,

42

subtractDependencies,

43

multiplyDependencies,

44

evaluateDependencies

45

})

46

```

47

48

### Direct Function Imports

49

```typescript

50

import { add, subtract, multiply, divide, evaluate, parse } from 'mathjs'

51

52

// Use functions directly

53

const result = add(2, 3) // 5

54

```

55

56

### Number-Only Build (Smaller Bundle)

57

```typescript

58

import { create, all } from 'mathjs/number'

59

const math = create(all)

60

```

61

62

## Basic Usage

63

64

### Simple Calculations

65

```typescript

66

import { evaluate, add, multiply, sqrt } from 'mathjs'

67

68

// Expression evaluation

69

evaluate('sqrt(3^2 + 4^2)') // 5

70

71

// Direct function calls

72

add(2, 3) // 5

73

multiply(4, 5) // 20

74

sqrt(16) // 4

75

```

76

77

### Working with Different Data Types

78

```typescript

79

import { create, all, BigNumber, Complex, Unit, Matrix } from 'mathjs'

80

const math = create(all)

81

82

// BigNumber for high precision

83

const big = math.bignumber('1.2345678901234567890')

84

85

// Complex numbers

86

const complex = math.complex(2, 3) // 2 + 3i

87

88

// Units with automatic conversion

89

const distance = math.unit('5 km')

90

math.to(distance, 'mile') // ~3.1 mile

91

92

// Matrices

93

const matrix = math.matrix([[1, 2], [3, 4]])

94

math.det(matrix) // -2

95

```

96

97

### Chaining Operations

98

```typescript

99

import { chain } from 'mathjs'

100

101

chain(3)

102

.add(4)

103

.multiply(2)

104

.done() // 14

105

```

106

107

## Architecture

108

109

Math.js uses a unique factory-based architecture that provides several key benefits:

110

111

### Factory System

112

```typescript

113

import { create, addDependencies, multiplyDependencies } from 'mathjs'

114

115

// Create custom math instance with only needed functions

116

const math = create({

117

addDependencies,

118

multiplyDependencies

119

})

120

```

121

122

### Configuration Options

123

```typescript

124

import { create, all } from 'mathjs'

125

126

const math = create(all, {

127

number: 'BigNumber', // Use BigNumber as default number type

128

precision: 64, // Number of significant digits

129

epsilon: 1e-60, // Minimum relative difference

130

matrix: 'Matrix', // Default matrix type

131

randomSeed: 'random' // Random number generator seed

132

})

133

```

134

135

### Type System

136

Math.js supports multiple number representations:

137

- **number**: JavaScript's built-in number type

138

- **BigNumber**: Arbitrary precision decimal numbers (via decimal.js)

139

- **bigint**: JavaScript BigInt for large integers

140

- **Fraction**: Exact fraction representation (via fraction.js)

141

- **Complex**: Complex number support with real and imaginary parts

142

143

## Core Capabilities

144

145

### Expression Parser and Evaluation

146

147

Parse and evaluate mathematical expressions with full JavaScript syntax support.

148

149

```typescript

150

import { evaluate, parse, compile } from 'mathjs'

151

152

// Direct evaluation

153

evaluate('2 + 3 * 4') // 14

154

evaluate('sqrt(3^2 + 4^2)') // 5

155

156

// Parse to AST then evaluate

157

const node = parse('2 + 3 * x')

158

node.evaluate({ x: 4 }) // 14

159

160

// Compile for performance

161

const compiled = compile('a * x^2 + b * x + c')

162

compiled.evaluate({ a: 1, b: -2, c: 1, x: 3 }) // 4

163

```

164

165

**Key Functions:**

166

- `evaluate(expr: string, scope?: object): any` { .api }

167

- `parse(expr: string, options?: ParseOptions): MathNode` { .api }

168

- `compile(expr: string | MathNode): EvalFunction` { .api }

169

170

See: [Expression Parser Documentation](expressions.md)

171

172

### Arithmetic Operations

173

174

Comprehensive set of arithmetic functions supporting all data types.

175

176

```typescript

177

import { add, subtract, multiply, divide, pow, sqrt } from 'mathjs'

178

179

// Basic operations work with any numeric type

180

add(2, 3) // 5

181

add('2', '3') // Error: strings not supported directly

182

add(math.bignumber('2'), math.bignumber('3')) // BigNumber(5)

183

184

// Advanced operations

185

pow(2, 8) // 256

186

sqrt(16) // 4

187

```

188

189

**Key Functions:**

190

- `add(x: MathType, y: MathType, ...rest: MathType[]): MathType` { .api }

191

- `subtract(x: MathType, y: MathType): MathType` { .api }

192

- `multiply(x: MathType, y: MathType, ...rest: MathType[]): MathType` { .api }

193

- `divide(x: MathType, y: MathType): MathType` { .api }

194

- `pow(x: MathType, y: MathType): MathType` { .api }

195

- `sqrt(x: MathType): MathType` { .api }

196

197

See: [Arithmetic Operations Documentation](arithmetic.md)

198

199

### Trigonometric Functions

200

201

Complete set of trigonometric, hyperbolic, and inverse functions.

202

203

```typescript

204

import { sin, cos, tan, asin, sinh, pi } from 'mathjs'

205

206

sin(pi / 2) // 1

207

cos(0) // 1

208

tan(pi / 4) // 1

209

asin(0.5) // π/6

210

sinh(0) // 0

211

```

212

213

**Key Functions:**

214

- `sin(x: MathType): MathType` { .api }

215

- `cos(x: MathType): MathType` { .api }

216

- `tan(x: MathType): MathType` { .api }

217

- `asin(x: MathType): MathType` { .api }

218

- `sinh(x: MathType): MathType` { .api }

219

220

See: [Trigonometry Documentation](trigonometry.md)

221

222

### Matrix Operations and Linear Algebra

223

224

Powerful matrix operations with support for dense and sparse matrices.

225

226

```typescript

227

import { matrix, multiply, det, inv, eigs } from 'mathjs'

228

229

const A = matrix([[1, 2], [3, 4]])

230

const B = matrix([[5, 6], [7, 8]])

231

232

multiply(A, B) // Matrix multiplication

233

det(A) // -2

234

inv(A) // Matrix inverse

235

eigs(A) // Eigenvalues and eigenvectors

236

```

237

238

**Key Functions:**

239

- `matrix(data: MathArray | Matrix, format?: 'dense' | 'sparse', dataType?: string): Matrix` { .api }

240

- `det(x: MathCollection): MathType` { .api }

241

- `inv(x: MathCollection): MathCollection` { .api }

242

- `eigs(x: MathCollection, options?: { precision?: number | BigNumber, eigenvectors?: boolean }): { values: MathCollection, eigenvectors?: Array<{value: MathType, vector: MathCollection}> }` { .api }

243

244

See: [Matrix Operations Documentation](matrices.md)

245

246

### Statistical Functions

247

248

Statistical analysis functions for data processing.

249

250

```typescript

251

import { mean, std, median, max, min } from 'mathjs'

252

253

const data = [1, 2, 3, 4, 5]

254

mean(data) // 3

255

std(data) // ~1.58

256

median(data) // 3

257

max(data) // 5

258

min(data) // 1

259

```

260

261

**Key Functions:**

262

- `mean(...values: MathType[]): MathType` { .api }

263

- `std(values: MathCollection, normalization?: 'uncorrected' | 'biased' | 'unbiased'): MathType` { .api }

264

- `median(...values: MathType[]): MathType` { .api }

265

266

See: [Statistics Documentation](statistics.md)

267

268

### Probability and Combinatorics

269

270

Functions for probability calculations and combinatorial operations.

271

272

```typescript

273

import { combinations, factorial, gamma, random } from 'mathjs'

274

275

combinations(10, 3) // 120

276

factorial(5) // 120

277

gamma(0.5) // √π

278

random() // Random number between 0 and 1

279

```

280

281

**Key Functions:**

282

- `combinations(n: MathType, k: MathType): MathType` { .api }

283

- `factorial(n: MathType): MathType` { .api }

284

- `gamma(n: MathType): MathType` { .api }

285

286

See: [Probability Documentation](probability.md)

287

288

### Unit System and Conversions

289

290

Comprehensive unit system with automatic conversions between compatible units.

291

292

```typescript

293

import { unit, to, createUnit } from 'mathjs'

294

295

// Create units

296

const distance = unit('5 km')

297

const time = unit('30 minutes')

298

299

// Convert between units

300

to(distance, 'mile') // ~3.1 mile

301

to(time, 'hour') // 0.5 hour

302

303

// Create custom units

304

createUnit('byte')

305

createUnit('kilobyte', '1024 byte')

306

```

307

308

**Key Functions:**

309

- `unit(value?: string | number, unit?: string): Unit` { .api }

310

- `to(value: Unit, unit: string | Unit): Unit` { .api }

311

- `createUnit(name: string, definition?: string | Unit | UnitDefinition, options?: CreateUnitOptions): Unit` { .api }

312

313

See: [Units and Conversions Documentation](units.md)

314

315

### Data Types and Type System

316

317

Math.js provides rich data type support with automatic type conversion and custom type creation.

318

319

```typescript

320

import { bignumber, complex, fraction, matrix, string, number } from 'mathjs'

321

322

// Type constructors

323

const big = bignumber('1.23456789012345678901234567890')

324

const comp = complex(2, 3) // 2 + 3i

325

const frac = fraction(1, 3) // 1/3

326

const mat = matrix([[1, 2], [3, 4]])

327

328

// Type conversions

329

number(frac) // 0.3333...

330

string(comp) // '2 + 3i'

331

```

332

333

**Key Functions:**

334

- `bignumber(value?: MathType): BigNumber` { .api }

335

- `complex(re: MathType, im?: MathType): Complex` { .api }

336

- `fraction(numerator: MathType, denominator?: MathType): Fraction` { .api }

337

- `number(value?: MathType, valuelessUnit?: Unit | string): number` { .api }

338

339

See: [Data Types Documentation](data-types.md)

340

341

## Constants

342

343

Math.js provides mathematical and physical constants:

344

345

### Mathematical Constants

346

```typescript

347

import { pi, e, i, phi, tau } from 'mathjs'

348

349

pi // π ≈ 3.14159

350

e // Euler's number ≈ 2.71828

351

i // Imaginary unit

352

phi // Golden ratio ≈ 1.618

353

tau // 2π ≈ 6.283

354

```

355

356

### Physical Constants

357

```typescript

358

import { speedOfLight, planckConstant, avogadro } from 'mathjs'

359

360

speedOfLight // Speed of light in vacuum

361

planckConstant // Planck constant

362

avogadro // Avogadro's number

363

```

364

365

## Type Definitions

366

367

### Core Types

368

```typescript

369

type MathNumericType = number | BigNumber | bigint | Fraction | Complex

370

type MathScalarType = MathNumericType | Unit

371

type MathArray<T = MathNumericType> = T[] | Array<MathArray<T>>

372

type MathCollection<T = MathNumericType> = MathArray<T> | Matrix<T>

373

type MathType = MathScalarType | MathCollection

374

type MathExpression = string | string[] | MathCollection

375

```

376

377

### Configuration Types

378

```typescript

379

interface ConfigOptions {

380

epsilon?: number

381

matrix?: 'Matrix' | 'Array'

382

number?: 'number' | 'BigNumber' | 'bigint' | 'Fraction'

383

precision?: number

384

predictable?: boolean

385

randomSeed?: string | null

386

relTol?: number

387

absTol?: number

388

}

389

```

390

391

### Function Types

392

```typescript

393

type FactoryFunction<T> = (scope: MathScope) => T

394

type EvalFunction = (scope?: MathScope) => any

395

type ParseOptions = {

396

nodes?: Record<string, MathNode>

397

}

398

```

399

400

## Error Handling

401

402

Math.js provides specific error types for different failure scenarios:

403

404

```typescript

405

import {

406

ArgumentsError,

407

DimensionError,

408

IndexError

409

} from 'mathjs'

410

411

try {

412

evaluate('1/0') // May throw various errors

413

} catch (error) {

414

if (error instanceof ArgumentsError) {

415

// Invalid function arguments

416

} else if (error instanceof DimensionError) {

417

// Matrix dimension mismatch

418

} else if (error instanceof IndexError) {

419

// Invalid array/matrix index

420

}

421

}

422

```

423

424

## Performance Considerations

425

426

### Tree Shaking

427

Use selective imports to reduce bundle size:

428

```typescript

429

// Good: Only imports needed functions

430

import { add, multiply } from 'mathjs'

431

432

// Avoid: Imports entire library

433

import * as math from 'mathjs'

434

```

435

436

### Compilation for Repeated Evaluation

437

```typescript

438

import { compile } from 'mathjs'

439

440

// Compile once, evaluate many times

441

const expr = compile('a * x^2 + b * x + c')

442

const results = inputs.map(input => expr.evaluate(input))

443

```

444

445

### Number-Only Build

446

For applications that only need basic number operations:

447

```typescript

448

import { create, all } from 'mathjs/number'

449

const math = create(all) // Smaller bundle, number-only operations

450

```