0
# Arithmetic Operations
1
2
This document covers all arithmetic operations available in Math.js, including basic operations, advanced mathematical functions, and element-wise operations for arrays and matrices.
3
4
## Import
5
6
```typescript
7
import {
8
add, subtract, multiply, divide, unaryMinus, unaryPlus,
9
pow, sqrt, cbrt, nthRoot, square, cube,
10
exp, expm1, log, log10, log2, log1p,
11
ceil, floor, round, fix,
12
abs, sign, mod,
13
gcd, lcm, xgcd, hypot, norm,
14
// Signal processing
15
fft, ifft, freqz, zpk2tf,
16
// Bitwise operations
17
bitAnd, bitOr, bitXor, bitNot, leftShift, rightArithShift, rightLogShift,
18
// Special functions
19
erf, zeta,
20
// Geometry
21
distance, intersect
22
} from 'mathjs'
23
```
24
25
## Basic Arithmetic Operations
26
27
### Addition
28
Adds two or more values. Supports variadic arguments and works with all numeric types.
29
30
```typescript
31
add(x: MathType, y: MathType, ...rest: MathType[]): MathType
32
```
33
{ .api }
34
35
```typescript
36
// Basic usage
37
add(2, 3) // 5
38
add(2, 3, 4) // 9
39
40
// With different types
41
add(bignumber('0.1'), bignumber('0.2')) // BigNumber(0.3)
42
add(complex(2, 3), complex(1, 1)) // Complex(3, 4) = 3 + 4i
43
44
// With matrices
45
add([[1, 2], [3, 4]], [[5, 6], [7, 8]]) // [[6, 8], [10, 12]]
46
47
// With units (must be compatible)
48
add(unit('5 cm'), unit('3 cm')) // 8 cm
49
```
50
51
### Subtraction
52
Subtracts the second value from the first.
53
54
```typescript
55
subtract(x: MathType, y: MathType): MathType
56
```
57
{ .api }
58
59
```typescript
60
subtract(5, 2) // 3
61
subtract(complex(3, 4), complex(1, 1)) // Complex(2, 3) = 2 + 3i
62
subtract([[5, 6], [7, 8]], [[1, 2], [3, 4]]) // [[4, 4], [4, 4]]
63
```
64
65
### Multiplication
66
Multiplies two or more values. For matrices, performs matrix multiplication.
67
68
```typescript
69
multiply(x: MathType, y: MathType, ...rest: MathType[]): MathType
70
```
71
{ .api }
72
73
```typescript
74
multiply(3, 4) // 12
75
multiply(2, 3, 4) // 24
76
77
// Matrix multiplication
78
multiply([[1, 2], [3, 4]], [[5, 6], [7, 8]])
79
// [[19, 22], [43, 50]]
80
81
// Units
82
multiply(unit('5 m'), unit('3 m')) // 15 m^2
83
```
84
85
### Division
86
Divides the first value by the second.
87
88
```typescript
89
divide(x: MathType, y: MathType): MathType
90
```
91
{ .api }
92
93
```typescript
94
divide(6, 2) // 3
95
divide(1, 3) // 0.3333...
96
divide(bignumber('1'), bignumber('3')) // BigNumber(0.33333...)
97
98
// Matrix division (multiplication by inverse)
99
divide([[4, 2], [6, 4]], [[1, 0], [0, 1]]) // [[4, 2], [6, 4]]
100
```
101
102
### Unary Operations
103
104
```typescript
105
unaryMinus(x: MathType): MathType
106
unaryPlus(x: MathType): MathType
107
```
108
{ .api }
109
110
```typescript
111
unaryMinus(5) // -5
112
unaryMinus(complex(3, 4)) // Complex(-3, -4) = -3 - 4i
113
114
unaryPlus(-5) // -5 (identity operation)
115
unaryPlus('5') // 5 (type conversion)
116
```
117
118
## Power and Root Operations
119
120
### Exponentiation
121
Raises the first argument to the power of the second.
122
123
```typescript
124
pow(x: MathType, y: MathType): MathType
125
```
126
{ .api }
127
128
```typescript
129
pow(2, 3) // 8
130
pow(4, 0.5) // 2 (square root)
131
pow(complex(2, 0), 3) // Complex(8, 0) = 8 + 0i
132
133
// Matrix power
134
pow([[1, 1], [1, 0]], 10) // 10th Fibonacci matrix
135
```
136
137
### Square Root
138
Calculates the square root of a value.
139
140
```typescript
141
sqrt(x: MathType): MathType
142
```
143
{ .api }
144
145
```typescript
146
sqrt(16) // 4
147
sqrt(-1) // Complex(0, 1) = i
148
sqrt(bignumber('2')) // BigNumber(1.41421...)
149
150
// Element-wise for arrays
151
sqrt([1, 4, 9, 16]) // [1, 2, 3, 4]
152
```
153
154
### Cube Root
155
Calculates the cube root of a value.
156
157
```typescript
158
cbrt(x: MathType): MathType
159
```
160
{ .api }
161
162
```typescript
163
cbrt(8) // 2
164
cbrt(-27) // -3
165
cbrt(complex(8, 0)) // Complex(2, 0)
166
```
167
168
### Nth Root
169
Calculates the nth root of a value.
170
171
```typescript
172
nthRoot(x: MathType, n: MathType): MathType
173
```
174
{ .api }
175
176
```typescript
177
nthRoot(16, 4) // 2 (fourth root)
178
nthRoot(32, 5) // 2 (fifth root)
179
nthRoot(-8, 3) // -2
180
```
181
182
### Square and Cube
183
Convenience functions for common powers.
184
185
```typescript
186
square(x: MathType): MathType
187
cube(x: MathType): MathType
188
```
189
{ .api }
190
191
```typescript
192
square(5) // 25
193
cube(3) // 27
194
195
// Element-wise operations
196
square([1, 2, 3, 4]) // [1, 4, 9, 16]
197
cube([1, 2, 3]) // [1, 8, 27]
198
```
199
200
## Exponential and Logarithmic Functions
201
202
### Exponential Functions
203
204
```typescript
205
exp(x: MathType): MathType
206
expm1(x: MathType): MathType // exp(x) - 1, more accurate for small x
207
```
208
{ .api }
209
210
```typescript
211
exp(1) // 2.71828... (e)
212
exp(0) // 1
213
exp(complex(0, pi)) // Complex(-1, 0) = -1 (Euler's formula)
214
215
expm1(1e-10) // More accurate than exp(1e-10) - 1
216
```
217
218
### Logarithmic Functions
219
220
```typescript
221
log(x: MathType, base?: MathType): MathType
222
log10(x: MathType): MathType
223
log2(x: MathType): MathType
224
log1p(x: MathType): MathType // log(1 + x), more accurate for small x
225
```
226
{ .api }
227
228
```typescript
229
log(e) // 1 (natural logarithm)
230
log(100, 10) // 2 (base-10 logarithm)
231
log2(8) // 3
232
log10(1000) // 3
233
234
log1p(1e-10) // More accurate than log(1 + 1e-10)
235
```
236
237
## Rounding Functions
238
239
All rounding functions support precision parameter and units.
240
241
### Ceiling
242
Rounds toward positive infinity.
243
244
```typescript
245
ceil(x: MathType, n?: number, unit?: Unit): MathType
246
```
247
{ .api }
248
249
```typescript
250
ceil(3.2) // 4
251
ceil(-3.2) // -3
252
ceil(3.141592, 2) // 3.15 (2 decimal places)
253
ceil(unit('5.7 cm'), unit('1 mm')) // 57 mm
254
```
255
256
### Floor
257
Rounds toward negative infinity.
258
259
```typescript
260
floor(x: MathType, n?: number, unit?: Unit): MathType
261
```
262
{ .api }
263
264
```typescript
265
floor(3.7) // 3
266
floor(-3.2) // -4
267
floor(3.141592, 2) // 3.14
268
```
269
270
### Round
271
Rounds to the nearest integer or specified precision.
272
273
```typescript
274
round(x: MathType, n?: number, unit?: Unit): MathType
275
```
276
{ .api }
277
278
```typescript
279
round(3.7) // 4
280
round(3.2) // 3
281
round(3.141592, 3) // 3.142
282
round(unit('5.67 m'), unit('1 cm')) // 567 cm
283
```
284
285
### Fix
286
Rounds toward zero (truncates).
287
288
```typescript
289
fix(x: MathType, n?: number, unit?: Unit): MathType
290
```
291
{ .api }
292
293
```typescript
294
fix(3.7) // 3
295
fix(-3.7) // -3
296
fix(3.141592, 2) // 3.14
297
```
298
299
## Element-wise Matrix Operations
300
301
For element-wise operations on matrices (as opposed to matrix algebra operations).
302
303
### Element-wise Division
304
305
```typescript
306
dotDivide(x: MathCollection, y: MathCollection): MathCollection
307
```
308
{ .api }
309
310
```typescript
311
dotDivide([[6, 8], [10, 12]], [[2, 4], [5, 3]])
312
// [[3, 2], [2, 4]]
313
```
314
315
### Element-wise Multiplication
316
317
```typescript
318
dotMultiply(x: MathCollection, y: MathCollection): MathCollection
319
```
320
{ .api }
321
322
```typescript
323
dotMultiply([[1, 2], [3, 4]], [[5, 6], [7, 8]])
324
// [[5, 12], [21, 32]]
325
```
326
327
### Element-wise Power
328
329
```typescript
330
dotPow(x: MathCollection, y: MathCollection): MathCollection
331
```
332
{ .api }
333
334
```typescript
335
dotPow([[2, 3], [4, 5]], [[2, 2], [3, 2]])
336
// [[4, 9], [64, 25]]
337
```
338
339
## Advanced Arithmetic Functions
340
341
### Absolute Value
342
343
```typescript
344
abs(x: MathType): MathType
345
```
346
{ .api }
347
348
```typescript
349
abs(-5) // 5
350
abs(complex(3, 4)) // 5 (magnitude)
351
abs([[-2, 3], [-4, 5]]) // [[2, 3], [4, 5]]
352
```
353
354
### Sign Function
355
356
```typescript
357
sign(x: MathType): MathType
358
```
359
{ .api }
360
361
```typescript
362
sign(5) // 1
363
sign(-3) // -1
364
sign(0) // 0
365
sign(complex(3, 4)) // Complex(0.6, 0.8) (unit vector)
366
```
367
368
### Modulo Operation
369
370
```typescript
371
mod(x: MathType, y: MathType): MathType
372
```
373
{ .api }
374
375
```typescript
376
mod(7, 3) // 1
377
mod(-7, 3) // 2 (always non-negative result)
378
mod(bignumber('17'), bignumber('5')) // BigNumber(2)
379
```
380
381
### Greatest Common Divisor
382
383
```typescript
384
gcd(...args: MathType[]): MathType
385
```
386
{ .api }
387
388
```typescript
389
gcd(12, 8) // 4
390
gcd(12, 8, 4) // 4
391
gcd([12, 8, 16]) // 4
392
```
393
394
### Least Common Multiple
395
396
```typescript
397
lcm(x: MathType, y: MathType): MathType
398
```
399
{ .api }
400
401
```typescript
402
lcm(12, 8) // 24
403
lcm(fraction(1, 3), fraction(1, 4)) // Fraction(1, 12)
404
```
405
406
### Extended GCD
407
Returns the extended Euclidean algorithm result.
408
409
```typescript
410
xgcd(a: MathType, b: MathType): { gcd: MathType, x: MathType, y: MathType }
411
```
412
{ .api }
413
414
```typescript
415
xgcd(12, 8)
416
// { gcd: 4, x: 1, y: -1 }
417
// Meaning: 12 * 1 + 8 * (-1) = 4
418
```
419
420
### Hypotenuse
421
Calculates the hypotenuse (Euclidean norm) of the arguments.
422
423
```typescript
424
hypot(...args: MathType[]): MathType
425
```
426
{ .api }
427
428
```typescript
429
hypot(3, 4) // 5
430
hypot(1, 1, 1) // √3 ≈ 1.732
431
hypot([3, 4]) // 5
432
```
433
434
### Vector/Matrix Norm
435
436
```typescript
437
norm(x: MathCollection, p?: number | 'fro'): MathType
438
```
439
{ .api }
440
441
```typescript
442
norm([3, 4]) // 5 (L2 norm by default)
443
norm([3, 4], 1) // 7 (L1 norm)
444
norm([3, 4], Infinity) // 4 (L∞ norm)
445
446
// Matrix norms
447
norm([[1, 2], [3, 4]]) // ~5.477 (Frobenius norm)
448
norm([[1, 2], [3, 4]], 'fro') // ~5.477 (explicit Frobenius)
449
```
450
451
## Type Conversion and Validation
452
453
### Numeric Type Conversion
454
455
```typescript
456
number(value?: MathType, valuelessUnit?: Unit | string): number
457
```
458
{ .api }
459
460
```typescript
461
number(fraction(1, 3)) // 0.3333...
462
number(bignumber('5.5')) // 5.5
463
number(unit('5 cm'), 'mm') // 50 (convert to mm, return number)
464
```
465
466
## Error Handling
467
468
Arithmetic operations can throw several types of errors:
469
470
```typescript
471
import { DimensionError, ArgumentsError } from 'mathjs'
472
473
try {
474
add([[1, 2]], [[1, 2, 3]]) // Different matrix dimensions
475
} catch (error) {
476
if (error instanceof DimensionError) {
477
console.log('Matrix dimensions do not match')
478
}
479
}
480
481
try {
482
divide(1, 0) // Division by zero
483
} catch (error) {
484
// May return Infinity or throw depending on configuration
485
}
486
```
487
488
## Performance Tips
489
490
### Use Appropriate Data Types
491
- Use `number` for general calculations (fastest)
492
- Use `BigNumber` only when precision is critical
493
- Use typed arrays for large datasets
494
495
### Avoid Unnecessary Conversions
496
```typescript
497
// Good: Keep same type throughout calculation
498
const a = bignumber('1.1')
499
const b = bignumber('2.2')
500
const result = add(a, b)
501
502
// Avoid: Mixed types cause conversions
503
const mixed = add(1.1, bignumber('2.2'))
504
```
505
506
### Element-wise vs Matrix Operations
507
```typescript
508
// Element-wise (faster for simple operations)
509
dotMultiply(A, B)
510
511
// Matrix multiplication (mathematical operation)
512
multiply(A, B)
513
```
514
515
## Signal Processing Functions
516
517
Math.js includes functions for digital signal processing and transform operations.
518
519
### Fast Fourier Transform
520
521
```typescript
522
fft(arr: MathArray): MathArray
523
ifft(arr: MathArray): MathArray
524
```
525
{ .api }
526
527
```typescript
528
// FFT and inverse FFT
529
const signal = [1, 2, 3, 4]
530
const transformed = fft(signal)
531
const recovered = ifft(transformed) // Should recover original signal
532
533
// Complex signals
534
const complexSignal = [complex(1, 0), complex(2, 1), complex(1, -1)]
535
const fftResult = fft(complexSignal)
536
```
537
538
### Frequency Response and Transfer Functions
539
540
```typescript
541
freqz(b: MathArray, a: MathArray, w?: MathArray): { h: MathArray, w: MathArray }
542
zpk2tf(z: MathArray, p: MathArray, k?: MathType): { b: MathArray, a: MathArray }
543
```
544
{ .api }
545
546
```typescript
547
// Frequency response of a digital filter
548
const b = [1, 2, 1] // Numerator coefficients
549
const a = [1, -0.5, 0.25] // Denominator coefficients
550
const { h, w } = freqz(b, a)
551
552
// Zero-pole-gain to transfer function
553
const zeros = [-1, 1]
554
const poles = [0.5, -0.5]
555
const gain = 2
556
const { b: num, a: den } = zpk2tf(zeros, poles, gain)
557
```
558
559
## Bitwise Operations
560
561
For integer bitwise operations (primarily for number and bigint types).
562
563
### Bitwise Logical Operations
564
565
```typescript
566
bitAnd(x: MathType, y: MathType): MathType
567
bitOr(x: MathType, y: MathType): MathType
568
bitXor(x: MathType, y: MathType): MathType
569
bitNot(x: MathType): MathType
570
```
571
{ .api }
572
573
```typescript
574
bitAnd(5, 3) // 1 (binary: 101 & 011 = 001)
575
bitOr(5, 3) // 7 (binary: 101 | 011 = 111)
576
bitXor(5, 3) // 6 (binary: 101 ^ 011 = 110)
577
bitNot(5) // -6 (two's complement)
578
```
579
580
### Bit Shift Operations
581
582
```typescript
583
leftShift(x: MathType, y: MathType): MathType
584
rightArithShift(x: MathType, y: MathType): MathType
585
rightLogShift(x: MathType, y: MathType): MathType
586
```
587
{ .api }
588
589
```typescript
590
leftShift(5, 2) // 20 (5 << 2: 101 -> 10100)
591
rightArithShift(20, 2) // 5 (20 >> 2: arithmetic right shift)
592
rightLogShift(20, 2) // 5 (20 >>> 2: logical right shift)
593
594
// Negative number arithmetic vs logical shift difference
595
rightArithShift(-8, 2) // -2 (sign bit preserved)
596
rightLogShift(-8, 2) // Large positive number (zero-fill)
597
```
598
599
## Special Mathematical Functions
600
601
Advanced mathematical functions beyond basic arithmetic.
602
603
### Error Function
604
605
```typescript
606
erf(x: MathType): MathType
607
```
608
{ .api }
609
610
```typescript
611
erf(0) // 0
612
erf(1) // ~0.8427 (error function at 1)
613
erf(Infinity) // 1
614
615
// Complementary error function: erfc(x) = 1 - erf(x)
616
// Can be computed as: subtract(1, erf(x))
617
```
618
619
### Riemann Zeta Function
620
621
```typescript
622
zeta(s: MathType): MathType
623
```
624
{ .api }
625
626
```typescript
627
zeta(2) // π²/6 ≈ 1.6449 (Basel problem)
628
zeta(4) // π⁴/90 ≈ 1.0823
629
// zeta(1) // Undefined (pole)
630
zeta(0) // -1/2
631
zeta(-1) // -1/12 (analytic continuation)
632
```
633
634
## Geometry Functions
635
636
Basic geometric calculations.
637
638
### Distance Calculation
639
640
```typescript
641
distance(x: MathArray, y: MathArray): MathType
642
```
643
{ .api }
644
645
```typescript
646
distance([0, 0], [3, 4]) // 5 (Euclidean distance)
647
distance([1, 2, 3], [4, 6, 8]) // √(9 + 16 + 25) = √50 ≈ 7.07
648
649
// Works with any dimension
650
distance([0], [5]) // 5 (1D distance)
651
```
652
653
### Line Intersection
654
655
```typescript
656
intersect(w: MathArray, x: MathArray, y: MathArray, z: MathArray): MathArray
657
```
658
{ .api }
659
660
```typescript
661
// Intersection of two lines in 2D: line through w-x and line through y-z
662
const p1 = [0, 0]
663
const p2 = [2, 2]
664
const p3 = [0, 2]
665
const p4 = [2, 0]
666
const intersection = intersect(p1, p2, p3, p4) // [1, 1]
667
```
668
669
## Chain Operations
670
671
All arithmetic functions are available in the chain interface:
672
673
```typescript
674
chain(5)
675
.add(3) // 8
676
.multiply(2) // 16
677
.sqrt() // 4
678
.done() // 4
679
```
680
681
## Constants Related to Arithmetic
682
683
```typescript
684
import { e, pi, phi, tau, Infinity, NaN } from 'mathjs'
685
686
e // Euler's number ≈ 2.71828
687
pi // π ≈ 3.14159
688
phi // Golden ratio ≈ 1.618
689
tau // 2π ≈ 6.283
690
Infinity // Positive infinity
691
NaN // Not a Number
692
```