UNPKG

48 kBPlain TextView Raw
1import {
2 create,
3 factory,
4 all,
5 MathJsFunctionName,
6 fractionDependencies,
7 addDependencies,
8 divideDependencies,
9 formatDependencies,
10 MathNode,
11 MathJsChain,
12 BigNumber,
13 MathCollection,
14 Complex,
15 Unit,
16 Fraction,
17 MathArray,
18 Index,
19 Matrix,
20 EvalFunction,
21 LUDecomposition,
22 QRDecomposition,
23 SLUDecomposition,
24 MathType,
25 MathNumericType,
26 ConstantNode,
27 OperatorNode,
28 OperatorNodeFn,
29 OperatorNodeOp,
30 SymbolNode,
31} from 'mathjs'
32import * as assert from 'assert'
33import { expectTypeOf } from 'expect-type'
34
35// This file serves a dual purpose:
36// 1) examples of how to use math.js in TypeScript
37// 2) tests for the TypeScript declarations provided by math.js
38
39/*
40Basic usage examples
41*/
42{
43 const math = create(all)
44
45 const m2by2 = [
46 [-1, 2],
47 [3, 1],
48 ]
49 const m2by3 = [
50 [1, 2, 3],
51 [4, 5, 6],
52 ]
53
54 // functions and constants
55 math.round(math.e, 3)
56 math.round(100.123, 3)
57 math.atan2(3, -3) / math.pi
58 math.log(10000, 10)
59 math.sqrt(-4)
60
61 math.pow(m2by2, 2)
62 const angle = 0.2
63 math.add(math.pow(math.sin(angle), 2), math.pow(math.cos(angle), 2))
64
65 // std and variance check
66
67 math.std(1, 2, 3)
68 math.std([1, 2, 3])
69 math.std([1, 2, 3], 'biased')
70 math.std([1, 2, 3], 0, 'biased')
71 math.std(m2by3, 1, 'unbiased')
72 math.std(m2by3, 1, 'uncorrected')
73 math.variance(1, 2, 3)
74 math.variance([1, 2, 3])
75 math.variance([1, 2, 3], 'biased')
76 math.variance([1, 2, 3], 0, 'biased')
77 math.variance(m2by3, 1, 'unbiased')
78 math.variance(m2by3, 1, 'uncorrected')
79
80 // std and variance on chain
81 math.chain([1, 2, 3]).std('unbiased')
82 math.chain(m2by3).std(0, 'biased').std(0, 'uncorrected')
83 math.chain(m2by3).std(0, 'biased').std(0, 'uncorrected')
84 math.chain([1, 2, 3]).std('unbiased')
85 math.chain(m2by3).variance(0, 'biased')
86 math.chain(m2by3).variance(1, 'uncorrected').variance('unbiased')
87
88 math.variance(math.variance(m2by3, 'uncorrected'))
89
90 // expressions
91 math.evaluate('1.2 * (2 + 4.5)')
92
93 // chained operations
94 const a = math.chain(3).add(4).multiply(2).done()
95 assert.strictEqual(a, 14)
96
97 // mixed use of different data types in functions
98 assert.deepStrictEqual(math.add(4, [5, 6]), [9, 10]) // number + Array
99 assert.deepStrictEqual(
100 math.multiply(math.unit('5 mm'), 3),
101 math.unit('15 mm')
102 ) // Unit * number
103 assert.deepStrictEqual(math.subtract([2, 3, 4], 5), [-3, -2, -1]) // Array - number
104 assert.deepStrictEqual(
105 math.add(math.matrix([2, 3]), [4, 5]),
106 math.matrix([6, 8])
107 ) // Matrix + Array
108
109 // narrowed type inference
110 const _b: math.Matrix = math.add(math.matrix([2]), math.matrix([3]))
111 const _c: math.Matrix = math.subtract(math.matrix([4]), math.matrix([5]))
112}
113
114/*
115Bignumbers examples
116*/
117{
118 // configure the default type of numbers as BigNumbers
119 const math = create(all, {
120 number: 'BigNumber',
121 precision: 20,
122 })
123
124 {
125 assert.deepStrictEqual(
126 math.add(math.bignumber(0.1), math.bignumber(0.2)),
127 math.bignumber(0.3)
128 )
129 assert.deepStrictEqual(
130 math.divide(math.bignumber(0.3), math.bignumber(0.2)),
131 math.bignumber(1.5)
132 )
133 }
134}
135
136/*
137Chaining examples
138*/
139{
140 const math = create(all, {})
141 const a = math.chain(3).add(4).multiply(2).done()
142 assert.strictEqual(a, 14)
143
144 // Another example, calculate square(sin(pi / 4))
145 const _b = math.chain(math.pi).divide(4).sin().square().done()
146
147 // toString will return a string representation of the chain's value
148 const chain = math.chain(2).divide(3)
149 const str: string = chain.toString()
150 assert.strictEqual(str, '0.6666666666666666')
151
152 chain.valueOf()
153
154 // the function subset can be used to get or replace sub matrices
155 const array = [
156 [1, 2],
157 [3, 4],
158 ]
159 const v = math.chain(array).subset(math.index(1, 0)).done()
160 assert.strictEqual(v, 3)
161
162 const _m = math.chain(array).subset(math.index(0, 0), 8).multiply(3).done()
163
164 // filtering
165 assert.deepStrictEqual(
166 math
167 .chain([-1, 0, 1.1, 2, 3, 1000])
168 .filter(math.isPositive)
169 .filter(math.isInteger)
170 .filter((n) => n !== 1000)
171 .done(),
172 [2, 3]
173 )
174
175 const r = math.chain(-0.483).round([0, 1, 2]).floor().add(0.52).fix(1).done()
176
177 assert.deepStrictEqual(r, [0.5, -0.4, -0.4])
178
179 expectTypeOf(
180 math.chain('x + y').parse().resolve({ x: 1 }).done()
181 ).toMatchTypeOf<MathNode>()
182 expectTypeOf(
183 math.chain('x + y').parse().resolve().done()
184 ).toMatchTypeOf<MathNode>()
185
186 // bignum
187 expectTypeOf(math.chain(math.bignumber(12))).toMatchTypeOf<
188 MathJsChain<BigNumber>
189 >()
190 expectTypeOf(math.chain(12).bignumber()).toMatchTypeOf<
191 MathJsChain<BigNumber>
192 >()
193 expectTypeOf(math.chain([12, 13, 14]).bignumber()).toMatchTypeOf<
194 MathJsChain<MathCollection>
195 >()
196
197 // chain
198 expectTypeOf(math.chain(12).bignumber().clone()).toMatchTypeOf<
199 MathJsChain<BigNumber>
200 >()
201
202 // boolean
203 expectTypeOf(math.chain(math.boolean(true))).toMatchTypeOf<
204 MathJsChain<boolean>
205 >()
206 expectTypeOf(math.chain(true).boolean()).toMatchTypeOf<MathJsChain<boolean>>()
207 expectTypeOf(math.chain([12, 13, 14]).boolean()).toMatchTypeOf<
208 MathJsChain<MathCollection>
209 >()
210
211 // complex
212 expectTypeOf(math.chain(math.complex('123'))).toMatchTypeOf<
213 MathJsChain<Complex>
214 >()
215 expectTypeOf(math.chain('123').complex()).toMatchTypeOf<
216 MathJsChain<Complex>
217 >()
218 expectTypeOf(math.chain('123').complex(1)).toMatchTypeOf<
219 MathJsChain<Complex>
220 >()
221 expectTypeOf(math.chain([12, 13, 14]).complex()).toMatchTypeOf<
222 MathJsChain<MathCollection>
223 >()
224
225 // createUnit
226 expectTypeOf(math.chain(math.createUnit('furlong'))).toMatchTypeOf<
227 MathJsChain<Unit>
228 >()
229 expectTypeOf(
230 math.chain(
231 math.createUnit({
232 fresnel: '1234',
233 })
234 )
235 ).toMatchTypeOf<MathJsChain<Unit>>()
236
237 // fraction
238 expectTypeOf(math.chain(math.fraction('123'))).toMatchTypeOf<
239 MathJsChain<Fraction>
240 >()
241 expectTypeOf(math.chain('123').fraction()).toMatchTypeOf<
242 MathJsChain<Fraction>
243 >()
244 expectTypeOf(math.chain('123').fraction(2)).toMatchTypeOf<
245 MathJsChain<Fraction>
246 >()
247 expectTypeOf(math.chain([12, 13, 14]).fraction()).toMatchTypeOf<
248 MathJsChain<MathCollection>
249 >()
250 expectTypeOf(math.chain([12, 13, 14]).fraction()).toMatchTypeOf<
251 MathJsChain<MathCollection>
252 >()
253
254 // index
255 expectTypeOf(math.chain([12, 13, 14]).index()).toMatchTypeOf<
256 MathJsChain<Index>
257 >()
258
259 // matrix
260 expectTypeOf(math.chain([12, 13, 14, 15]).matrix()).toMatchTypeOf<
261 MathJsChain<Matrix>
262 >()
263
264 // number
265 expectTypeOf(math.chain('12').number()).toMatchTypeOf<MathJsChain<number>>()
266 expectTypeOf(math.chain([12, 13, 14]).number()).toMatchTypeOf<
267 MathJsChain<MathCollection>
268 >()
269
270 // sparse
271 expectTypeOf(math.chain([12, 13, 14, 15]).sparse()).toMatchTypeOf<
272 MathJsChain<Matrix>
273 >()
274
275 // split unit
276 expectTypeOf(math.chain(math.unit('furlong')).splitUnit([])).toMatchTypeOf<
277 MathJsChain<Unit[]>
278 >()
279
280 // string
281 expectTypeOf(math.chain('test').string()).toMatchTypeOf<MathJsChain<string>>()
282 expectTypeOf(math.chain([1, 2, 3]).string()).toMatchTypeOf<
283 MathJsChain<MathCollection>
284 >()
285
286 // unit
287 expectTypeOf(math.chain(12).unit()).toMatchTypeOf<MathJsChain<Unit>>()
288 expectTypeOf(math.chain([1, 2, 3]).unit()).toMatchTypeOf<
289 MathJsChain<Unit[]>
290 >()
291
292 // compile
293 expectTypeOf(math.chain('a + b').compile()).toMatchTypeOf<
294 MathJsChain<EvalFunction>
295 >()
296
297 // evaluate
298 // eslint-disable-next-line @typescript-eslint/no-explicit-any
299 expectTypeOf(math.chain('1 + 1').evaluate()).toMatchTypeOf<MathJsChain<any>>()
300 expectTypeOf(math.chain(['1 + 1', '2 + 2']).evaluate()).toMatchTypeOf<
301 // eslint-disable-next-line @typescript-eslint/no-explicit-any
302 MathJsChain<any[]>
303 >()
304
305 // parse
306 expectTypeOf(math.chain('1 + 1').parse()).toMatchTypeOf<
307 MathJsChain<MathNode>
308 >()
309 expectTypeOf(math.chain(['1 + 1', '2 + 2']).parse()).toMatchTypeOf<
310 MathJsChain<MathNode[]>
311 >()
312
313 // resolve
314 expectTypeOf(math.chain(math.parse('1 + 1')).resolve({})).toMatchTypeOf<
315 MathJsChain<MathNode>
316 >()
317 expectTypeOf(
318 math.chain([math.parse('1 + 1'), math.parse('1 + 1')]).resolve({})
319 ).toMatchTypeOf<MathJsChain<MathNode[]>>()
320
321 // derivative
322 expectTypeOf(math.chain(math.parse('x^2')).derivative('x')).toMatchTypeOf<
323 MathJsChain<MathNode>
324 >()
325
326 // lsolve
327 expectTypeOf(
328 math
329 .chain([
330 [1, 2],
331 [3, 4],
332 ])
333 .lsolve([1, 2])
334 ).toMatchTypeOf<MathJsChain<MathArray>>()
335 expectTypeOf(
336 math
337 .chain(
338 math.matrix([
339 [1, 2],
340 [3, 4],
341 ])
342 )
343 .lsolve([1, 2])
344 ).toMatchTypeOf<MathJsChain<Matrix>>()
345
346 // lup
347 expectTypeOf(
348 math
349 .chain([
350 [1, 2],
351 [3, 4],
352 ])
353 .lup()
354 ).toMatchTypeOf<MathJsChain<LUDecomposition>>()
355 expectTypeOf(
356 math
357 .chain(
358 math.matrix([
359 [1, 2],
360 [3, 4],
361 ])
362 )
363 .lup()
364 ).toMatchTypeOf<MathJsChain<LUDecomposition>>()
365
366 // lusolve
367 expectTypeOf(
368 math
369 .chain(
370 math.matrix([
371 [1, 2],
372 [3, 4],
373 ])
374 )
375 .lusolve(math.matrix([1, 2]))
376 ).toMatchTypeOf<MathJsChain<Matrix>>()
377
378 expectTypeOf(
379 math
380 .chain(
381 math.matrix([
382 [1, 2],
383 [3, 4],
384 ])
385 )
386 .lusolve([1, 2])
387 ).toMatchTypeOf<MathJsChain<Matrix>>()
388
389 expectTypeOf(
390 math
391 .chain([
392 [1, 2],
393 [3, 4],
394 ])
395 .lusolve(math.matrix([1, 2]))
396 ).toMatchTypeOf<MathJsChain<MathArray>>()
397
398 expectTypeOf(
399 math
400 .chain([
401 [1, 2],
402 [3, 4],
403 ])
404 .lusolve([1, 2])
405 ).toMatchTypeOf<MathJsChain<MathArray>>()
406
407 // qr
408 expectTypeOf(
409 math
410 .chain([
411 [1, 2],
412 [3, 4],
413 ])
414 .qr()
415 ).toMatchTypeOf<MathJsChain<QRDecomposition>>()
416 expectTypeOf(
417 math
418 .chain(
419 math.matrix([
420 [1, 2],
421 [3, 4],
422 ])
423 )
424 .qr()
425 ).toMatchTypeOf<MathJsChain<QRDecomposition>>()
426
427 // rationalize
428 expectTypeOf(math.chain('1.23').rationalize()).toMatchTypeOf<
429 MathJsChain<MathNode>
430 >()
431 expectTypeOf(math.chain(math.parse('1.23')).rationalize()).toMatchTypeOf<
432 MathJsChain<MathNode>
433 >()
434
435 // simplify
436 expectTypeOf(math.chain('a + a + b').simplify()).toMatchTypeOf<
437 MathJsChain<MathNode>
438 >()
439 expectTypeOf(math.chain(math.parse('a + a + b')).simplify()).toMatchTypeOf<
440 MathJsChain<MathNode>
441 >()
442
443 // slu
444 expectTypeOf(
445 math
446 .chain(
447 math.sparse([
448 [1, 2],
449 [3, 4],
450 ])
451 )
452 .slu(2, 0.5)
453 ).toMatchTypeOf<MathJsChain<SLUDecomposition>>()
454
455 // usolve
456 expectTypeOf(
457 math
458 .chain([
459 [1, 2],
460 [3, 4],
461 ])
462 .usolve([1, 2])
463 ).toMatchTypeOf<MathJsChain<MathArray>>()
464 expectTypeOf(
465 math
466 .chain(
467 math.matrix([
468 [1, 2],
469 [3, 4],
470 ])
471 )
472 .usolve([1, 2])
473 ).toMatchTypeOf<MathJsChain<Matrix>>()
474
475 // abs
476 expectTypeOf(math.chain(1).abs()).toMatchTypeOf<MathJsChain<number>>()
477 expectTypeOf(math.chain(math.bignumber(1)).abs()).toMatchTypeOf<
478 MathJsChain<BigNumber>
479 >()
480 expectTypeOf(math.chain(math.fraction(1, 2)).abs()).toMatchTypeOf<
481 MathJsChain<Fraction>
482 >()
483 expectTypeOf(math.chain(math.complex(1, 2)).abs()).toMatchTypeOf<
484 MathJsChain<Complex>
485 >()
486 expectTypeOf(math.chain([1, 2]).abs()).toMatchTypeOf<MathJsChain<MathArray>>()
487 expectTypeOf(
488 math
489 .chain(
490 math.matrix([
491 [1, 2],
492 [3, 4],
493 ])
494 )
495 .abs()
496 ).toMatchTypeOf<MathJsChain<Matrix>>()
497 expectTypeOf(math.chain(math.unit('furlong')).abs()).toMatchTypeOf<
498 MathJsChain<Unit>
499 >()
500
501 // add
502 expectTypeOf(math.chain(1).add(2)).toMatchTypeOf<MathJsChain<MathType>>()
503 expectTypeOf(math.chain([1]).add(2)).toMatchTypeOf<MathJsChain<MathType>>()
504 expectTypeOf(
505 math.chain(
506 math.matrix([
507 [1, 2],
508 [3, 4],
509 ])
510 )
511 ).toMatchTypeOf<MathJsChain<Matrix>>()
512
513 // apply
514 expectTypeOf(math.chain([1, 2, 3]).apply(0, () => 1)).toMatchTypeOf<
515 MathJsChain<number[]>
516 >()
517
518 // cbrt
519 expectTypeOf(math.chain(1).cbrt()).toMatchTypeOf<MathJsChain<number>>()
520 expectTypeOf(math.chain(math.bignumber(1)).cbrt()).toMatchTypeOf<
521 MathJsChain<BigNumber>
522 >()
523 expectTypeOf(math.chain(math.complex(1, 2)).cbrt()).toMatchTypeOf<
524 MathJsChain<Complex>
525 >()
526 expectTypeOf(math.chain([1, 2]).cbrt()).toMatchTypeOf<
527 MathJsChain<MathArray>
528 >()
529 expectTypeOf(
530 math
531 .chain(
532 math.matrix([
533 [1, 2],
534 [3, 4],
535 ])
536 )
537 .cbrt()
538 ).toMatchTypeOf<MathJsChain<Matrix>>()
539
540 // cbrt
541 expectTypeOf(math.chain(1).ceil()).toMatchTypeOf<
542 MathJsChain<MathNumericType>
543 >()
544 expectTypeOf(math.chain([1]).ceil()).toMatchTypeOf<
545 MathJsChain<MathCollection>
546 >()
547
548 // fix
549 expectTypeOf(math.chain(1).fix()).toMatchTypeOf<
550 MathJsChain<MathNumericType>
551 >()
552 expectTypeOf(math.chain([1]).fix()).toMatchTypeOf<
553 MathJsChain<MathCollection>
554 >()
555
556 // floor
557 expectTypeOf(math.chain(1).floor()).toMatchTypeOf<
558 MathJsChain<MathNumericType>
559 >()
560 expectTypeOf(math.chain([1]).floor()).toMatchTypeOf<
561 MathJsChain<MathCollection>
562 >()
563
564 // round
565 expectTypeOf(math.chain(1).round()).toMatchTypeOf<
566 MathJsChain<MathNumericType>
567 >()
568 expectTypeOf(math.chain([1]).round()).toMatchTypeOf<
569 MathJsChain<MathCollection>
570 >()
571
572 // cube
573 expectTypeOf(math.chain(1).cube()).toMatchTypeOf<MathJsChain<number>>()
574 expectTypeOf(math.chain(math.bignumber(1)).cube()).toMatchTypeOf<
575 MathJsChain<BigNumber>
576 >()
577 expectTypeOf(math.chain(math.fraction(1, 2)).cube()).toMatchTypeOf<
578 MathJsChain<Fraction>
579 >()
580 expectTypeOf(math.chain(math.complex(1, 2)).cube()).toMatchTypeOf<
581 MathJsChain<Complex>
582 >()
583 expectTypeOf(math.chain([1, 2]).cube()).toMatchTypeOf<
584 MathJsChain<MathArray>
585 >()
586 expectTypeOf(
587 math
588 .chain(
589 math.matrix([
590 [1, 2],
591 [3, 4],
592 ])
593 )
594 .cube()
595 ).toMatchTypeOf<MathJsChain<Matrix>>()
596 expectTypeOf(math.chain(math.unit('furlong')).cube()).toMatchTypeOf<
597 MathJsChain<Unit>
598 >()
599
600 // divide
601 expectTypeOf(
602 math.chain(math.unit('furlong')).divide(math.unit('femtosecond'))
603 ).toMatchTypeOf<MathJsChain<number | Unit>>()
604 expectTypeOf(math.chain(math.unit('furlong')).divide(6)).toMatchTypeOf<
605 MathJsChain<Unit>
606 >()
607 expectTypeOf(math.chain(2).divide(6)).toMatchTypeOf<MathJsChain<number>>()
608 expectTypeOf(math.chain([1, 2, 3]).divide(6)).toMatchTypeOf<
609 MathJsChain<MathType>
610 >()
611
612 // dotDivide
613 expectTypeOf(math.chain(1).dotDivide(2)).toMatchTypeOf<
614 MathJsChain<MathType>
615 >()
616 expectTypeOf(
617 math
618 .chain(
619 math.matrix([
620 [1, 2],
621 [3, 4],
622 ])
623 )
624 .dotDivide(2)
625 ).toMatchTypeOf<MathJsChain<MathType>>()
626
627 // dotMultiply
628 expectTypeOf(math.chain(1).dotMultiply(2)).toMatchTypeOf<
629 MathJsChain<MathType>
630 >()
631 expectTypeOf(
632 math
633 .chain(
634 math.matrix([
635 [1, 2],
636 [3, 4],
637 ])
638 )
639 .dotMultiply(2)
640 ).toMatchTypeOf<MathJsChain<MathType>>()
641
642 // dotPow
643 expectTypeOf(math.chain(1).dotPow(2)).toMatchTypeOf<MathJsChain<MathType>>()
644 expectTypeOf(
645 math
646 .chain(
647 math.matrix([
648 [1, 2],
649 [3, 4],
650 ])
651 )
652 .dotPow(2)
653 ).toMatchTypeOf<MathJsChain<MathType>>()
654
655 // exp
656 expectTypeOf(math.chain(1).exp()).toMatchTypeOf<MathJsChain<MathType>>()
657 expectTypeOf(math.chain([1, 2]).exp()).toMatchTypeOf<MathJsChain<MathArray>>()
658 expectTypeOf(
659 math
660 .chain(
661 math.matrix([
662 [1, 2],
663 [3, 4],
664 ])
665 )
666 .exp()
667 ).toMatchTypeOf<MathJsChain<Matrix>>()
668
669 // expm1
670 expectTypeOf(math.chain(1).expm1()).toMatchTypeOf<MathJsChain<MathType>>()
671 expectTypeOf(math.chain([1, 2]).expm1()).toMatchTypeOf<
672 MathJsChain<MathArray>
673 >()
674 expectTypeOf(
675 math
676 .chain(
677 math.matrix([
678 [1, 2],
679 [3, 4],
680 ])
681 )
682 .expm1()
683 ).toMatchTypeOf<MathJsChain<Matrix>>()
684
685 // gcd
686 expectTypeOf(math.chain([1, 2]).gcd(3)).toMatchTypeOf<MathJsChain<number>>()
687 expectTypeOf(math.chain([1, 2]).gcd(3, 4)).toMatchTypeOf<
688 MathJsChain<number>
689 >()
690 // TODO make gcd() work in the following cases
691 // expectTypeOf(math.chain([1, 2]).gcd()).toMatchTypeOf<MathJsChain<number>>()
692 // expectTypeOf(math.chain([[1], [2]]).gcd()).toMatchTypeOf<
693 // MathJsChain<MathArray>
694 // >()
695 // expectTypeOf(
696 // math.chain([math.bignumber(1), math.bignumber(1)]).gcd()
697 // ).toMatchTypeOf<MathJsChain<BigNumber>>()
698 // expectTypeOf(
699 // math.chain([math.complex(1, 2), math.complex(1, 2)]).gcd()
700 // ).toMatchTypeOf<MathJsChain<Complex>>()
701 // expectTypeOf(
702 // math
703 // .chain(
704 // math.matrix([
705 // [1, 2],
706 // [3, 4],
707 // ])
708 // )
709 // .expm1()
710 // ).toMatchTypeOf<MathJsChain<Matrix>>()
711
712 // hypot
713 expectTypeOf(math.chain([1, 2]).hypot()).toMatchTypeOf<MathJsChain<number>>()
714 expectTypeOf(
715 math.chain([math.bignumber(1), math.bignumber(1)]).hypot()
716 ).toMatchTypeOf<MathJsChain<BigNumber>>()
717
718 // lcm
719 expectTypeOf(math.chain(1).lcm(2)).toMatchTypeOf<MathJsChain<number>>()
720 expectTypeOf(
721 math.chain(math.bignumber(1)).lcm(math.bignumber(2))
722 ).toMatchTypeOf<MathJsChain<BigNumber>>()
723 expectTypeOf(math.chain([1, 2]).lcm([3, 4])).toMatchTypeOf<
724 MathJsChain<MathArray>
725 >()
726 expectTypeOf(
727 math
728 .chain(
729 math.matrix([
730 [1, 2],
731 [3, 4],
732 ])
733 )
734 .lcm(
735 math.matrix([
736 [1, 2],
737 [3, 4],
738 ])
739 )
740 ).toMatchTypeOf<MathJsChain<Matrix>>()
741
742 // log
743 expectTypeOf(math.chain(1).log(2)).toMatchTypeOf<MathJsChain<number>>()
744 expectTypeOf(
745 math.chain(math.bignumber(1)).log(math.bignumber(2))
746 ).toMatchTypeOf<MathJsChain<BigNumber>>()
747
748 // log10
749 expectTypeOf(math.chain(1).log10()).toMatchTypeOf<MathJsChain<number>>()
750 expectTypeOf(math.chain(math.bignumber(1)).log10()).toMatchTypeOf<
751 MathJsChain<BigNumber>
752 >()
753 expectTypeOf(math.chain([1, 2]).log10()).toMatchTypeOf<
754 MathJsChain<MathArray>
755 >()
756 expectTypeOf(
757 math
758 .chain(
759 math.matrix([
760 [1, 2],
761 [3, 4],
762 ])
763 )
764 .log10()
765 ).toMatchTypeOf<MathJsChain<Matrix>>()
766
767 // TODO complete the rest of these...
768}
769
770/*
771Simplify examples
772*/
773{
774 const math = create(all)
775
776 math.simplify('2 * 1 * x ^ (2 - 1)')
777 math.simplify('2 * 3 * x', { x: 4 })
778
779 const f = math.parse('2 * 1 * x ^ (2 - 1)')
780 math.simplify(f)
781
782 math.simplify('0.4 * x', {}, { exactFractions: true })
783 math.simplify('0.4 * x', {}, { exactFractions: false })
784}
785
786/*
787Complex numbers examples
788*/
789{
790 const math = create(all, {})
791 const a = math.complex(2, 3)
792 // create a complex number by providing a string with real and complex parts
793 const b = math.complex('3 - 7i')
794
795 // read the real and complex parts of the complex number
796 {
797 const _x: number = a.re
798 const _y: number = a.im
799
800 // adjust the complex value
801 a.re = 5
802 }
803
804 // clone a complex value
805 {
806 const _clone = a.clone()
807 }
808
809 // perform operations with complex numbers
810 {
811 math.add(a, b)
812 math.multiply(a, b)
813 math.sin(a)
814 }
815
816 // create a complex number from polar coordinates
817 {
818 const p: math.PolarCoordinates = { r: math.sqrt(2), phi: math.pi / 4 }
819 const _c: math.Complex = math.complex(p)
820 }
821
822 // get polar coordinates of a complex number
823 {
824 const _p: math.PolarCoordinates = math.complex(3, 4).toPolar()
825 }
826}
827
828/*
829Expressions examples
830*/
831{
832 const math = create(all, {})
833 // evaluate expressions
834 {
835 math.evaluate('sqrt(3^2 + 4^2)')
836 }
837
838 // evaluate multiple expressions at once
839 {
840 math.evaluate(['f = 3', 'g = 4', 'f * g'])
841 }
842
843 // get content of a parenthesis node
844 {
845 const node = math.parse('(1)')
846 if (node.type !== 'ParenthesisNode') {
847 throw Error(`expected ParenthesisNode, got ${node.type}`)
848 }
849 const _innerNode = node.content
850 }
851
852 // scope can contain both variables and functions
853 {
854 const scope = { hello: (name: string) => `hello, ${name}!` }
855 assert.strictEqual(math.evaluate('hello("hero")', scope), 'hello, hero!')
856 }
857
858 // define a function as an expression
859 {
860 // eslint-disable-next-line @typescript-eslint/no-explicit-any
861 const scope: any = {
862 a: 3,
863 b: 4,
864 }
865 const f = math.evaluate('f(x) = x ^ a', scope)
866 f(2)
867 scope.f(2)
868 }
869
870 {
871 const node2 = math.parse('x^a')
872 const _code2: math.EvalFunction = node2.compile()
873 node2.toString()
874 }
875
876 // 3. using function math.compile
877 // parse an expression
878 {
879 // provide a scope for the variable assignment
880 const code2 = math.compile('a = a + 3')
881 const scope = { a: 7 }
882 code2.evaluate(scope)
883 }
884 // 4. using a parser
885 const parser = math.parser()
886
887 // get and set variables and functions
888 {
889 assert.strictEqual(parser.evaluate('x = 7 / 2'), 3.5)
890 assert.strictEqual(parser.evaluate('x + 3'), 6.5)
891 parser.evaluate('f(x, y) = x^y') // f(x, y)
892 assert.strictEqual(parser.evaluate('f(2, 3)'), 8)
893
894 const _x = parser.get('x')
895 const f = parser.get('f')
896 const _y = parser.getAll()
897 const _g = f(3, 3)
898
899 parser.set('h', 500)
900 parser.set('hello', (name: string) => `hello, ${name}!`)
901 }
902
903 // clear defined functions and variables
904 parser.clear()
905}
906
907/*
908Fractions examples
909*/
910{
911 // configure the default type of numbers as Fractions
912 const math = create(all, {
913 number: 'Fraction',
914 })
915
916 const x = math.fraction(0.125)
917 const y = math.fraction('1/3')
918 math.fraction(2, 3)
919
920 math.add(x, y)
921 math.divide(x, y)
922
923 // output formatting
924 const _a = math.fraction('2/3')
925}
926
927/*
928Matrices examples
929*/
930{
931 const math = create(all, {})
932
933 // create matrices and arrays. a matrix is just a wrapper around an Array,
934 // providing some handy utilities.
935 const a: math.Matrix = math.matrix([1, 4, 9, 16, 25])
936 const b: math.Matrix = math.matrix(math.ones([2, 3]))
937 b.size()
938
939 // the Array data of a Matrix can be retrieved using valueOf()
940 const _array = a.valueOf()
941
942 // Matrices can be cloned
943 const _clone: math.Matrix = a.clone()
944
945 // perform operations with matrices
946 math.sqrt(a)
947 math.factorial(a)
948
949 // create and manipulate matrices. Arrays and Matrices can be used mixed.
950 {
951 const a = [
952 [1, 2],
953 [3, 4],
954 ]
955 const b: math.Matrix = math.matrix([
956 [5, 6],
957 [1, 1],
958 ])
959
960 b.subset(math.index(1, [0, 1]), [[7, 8]])
961 const _c = math.multiply(a, b)
962 const f: math.Matrix = math.matrix([1, 0])
963 const _d: math.Matrix = f.subset(math.index(1))
964 }
965
966 // get a sub matrix
967 {
968 const a: math.Matrix = math.diag(math.range(1, 4))
969 a.subset(math.index([1, 2], [1, 2]))
970 const b: math.Matrix = math.range(1, 6)
971 b.subset(math.index(math.range(1, 4)))
972 }
973
974 // resize a multi dimensional matrix
975 {
976 const a = math.matrix()
977 a.resize([2, 2, 2], 0)
978 a.size()
979 a.resize([2, 2])
980 a.size()
981 }
982
983 // can set a subset of a matrix to uninitialized
984 {
985 const m = math.matrix()
986 m.subset(math.index(2), 6, math.uninitialized)
987 }
988
989 // create ranges
990 {
991 math.range(1, 6)
992 math.range(0, 18, 3)
993 math.range('2:-1:-3')
994 math.factorial(math.range('1:6'))
995 }
996
997 // map matrix
998 {
999 assert.deepStrictEqual(
1000 math.map([1, 2, 3], function (value) {
1001 return value * value
1002 }),
1003 [1, 4, 9]
1004 )
1005 }
1006
1007 // filter matrix
1008 {
1009 assert.deepStrictEqual(
1010 math.filter([6, -2, -1, 4, 3], function (x) {
1011 return x > 0
1012 }),
1013 [6, 4, 3]
1014 )
1015 assert.deepStrictEqual(
1016 math.filter(['23', 'foo', '100', '55', 'bar'], /[0-9]+/),
1017 ['23', '100', '55']
1018 )
1019 }
1020
1021 // concat matrix
1022 {
1023 assert.deepStrictEqual(math.concat([[0, 1, 2]], [[1, 2, 3]]), [
1024 [0, 1, 2, 1, 2, 3],
1025 ])
1026 assert.deepStrictEqual(math.concat([[0, 1, 2]], [[1, 2, 3]], 0), [
1027 [0, 1, 2],
1028 [1, 2, 3],
1029 ])
1030 }
1031
1032 // Matrix is available as a constructor for instanceof checks
1033 {
1034 assert.strictEqual(math.matrix([1, 2, 3]) instanceof math.Matrix, true)
1035 }
1036
1037 // Fourier transform and inverse
1038 {
1039 assert.ok(
1040 math.deepEqual(
1041 math.fft([
1042 [1, 0],
1043 [1, 0],
1044 ]),
1045 [
1046 [math.complex(2, 0), math.complex(2, 0)],
1047 [math.complex(0, 0), math.complex(0, 0)],
1048 ]
1049 )
1050 )
1051 assert.ok(
1052 math.deepEqual(
1053 math.fft(
1054 math.matrix([
1055 [1, 0],
1056 [1, 0],
1057 ])
1058 ),
1059 math.matrix([
1060 [math.complex(2, 0), math.complex(2, 0)],
1061 [math.complex(0, 0), math.complex(0, 0)],
1062 ])
1063 )
1064 )
1065 assert.ok(
1066 math.deepEqual(
1067 math.ifft([
1068 [2, 2],
1069 [0, 0],
1070 ]),
1071 [
1072 [math.complex(1, 0), math.complex(0, 0)],
1073 [math.complex(1, 0), math.complex(0, 0)],
1074 ]
1075 )
1076 )
1077 assert.ok(
1078 math.deepEqual(
1079 math.ifft(
1080 math.matrix([
1081 [2, 2],
1082 [0, 0],
1083 ])
1084 ),
1085 math.matrix([
1086 [math.complex(1, 0), math.complex(0, 0)],
1087 [math.complex(1, 0), math.complex(0, 0)],
1088 ])
1089 )
1090 )
1091 }
1092}
1093
1094/*
1095Sparse matrices examples
1096*/
1097{
1098 const math = create(all, {})
1099
1100 // create a sparse matrix
1101 const a = math.identity(1000, 1000, 'sparse')
1102
1103 // do operations with a sparse matrix
1104 const b = math.multiply(a, a)
1105 const _c = math.multiply(b, math.complex(2, 2))
1106 const d = math.matrix([0, 1])
1107 const e = math.transpose(d)
1108 const _f = math.multiply(e, d)
1109}
1110
1111/*
1112Units examples
1113*/
1114{
1115 const math = create(all, {})
1116
1117 // units can be created by providing a value and unit name, or by providing
1118 // a string with a valued unit.
1119 const a = math.unit(45, 'cm') // 450 mm
1120 const b = math.unit('0.1m') // 100 mm
1121 const _c = math.unit(b)
1122
1123 // creating units
1124 math.createUnit('foo')
1125 math.createUnit('furlong', '220 yards')
1126 math.createUnit('furlong', '220 yards', { override: true })
1127 math.createUnit('testunit', { definition: '0.555556 kelvin', offset: 459.67 })
1128 math.createUnit(
1129 'testunit',
1130 { definition: '0.555556 kelvin', offset: 459.67 },
1131 { override: true }
1132 )
1133 math.createUnit('knot', {
1134 definition: '0.514444 m/s',
1135 aliases: ['knots', 'kt', 'kts'],
1136 })
1137 math.createUnit(
1138 'knot',
1139 { definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts'] },
1140 { override: true }
1141 )
1142 math.createUnit(
1143 'knot',
1144 {
1145 definition: '0.514444 m/s',
1146 aliases: ['knots', 'kt', 'kts'],
1147 prefixes: 'long',
1148 },
1149 { override: true }
1150 )
1151 math.createUnit(
1152 {
1153 foo2: {
1154 prefixes: 'long',
1155 },
1156 bar: '40 foo',
1157 baz: {
1158 definition: '1 bar/hour',
1159 prefixes: 'long',
1160 },
1161 },
1162 {
1163 override: true,
1164 }
1165 )
1166 // use Unit as definition
1167 math.createUnit('c', { definition: b })
1168 math.createUnit('c', { definition: b }, { override: true })
1169
1170 // units can be added, subtracted, and multiplied or divided by numbers and by other units
1171 math.add(a, b)
1172 math.multiply(b, 2)
1173 math.divide(math.unit('1 m'), math.unit('1 s'))
1174 math.pow(math.unit('12 in'), 3)
1175
1176 // units can be converted to a specific type, or to a number
1177 b.to('cm')
1178 math.to(b, 'inch')
1179 b.toNumber('cm')
1180 math.number(b, 'cm')
1181
1182 // the expression parser supports units too
1183 math.evaluate('2 inch to cm')
1184
1185 // units can be converted to SI
1186 math.unit('1 inch').toSI()
1187
1188 // units can be split into other units
1189 math.unit('1 m').splitUnit(['ft', 'in'])
1190}
1191
1192/*
1193Expression tree examples
1194*/
1195{
1196 const math = create(all, {})
1197
1198 // Filter an expression tree
1199 const node: math.MathNode = math.parse('x^2 + x/4 + 3*y')
1200 const filtered: math.MathNode[] = node.filter(
1201 (node: math.MathNode) => node.type === 'SymbolNode' && node.name === 'x'
1202 )
1203
1204 const _arr: string[] = filtered.map((node: math.MathNode) => node.toString())
1205
1206 // Traverse an expression tree
1207 const node1: math.MathNode = math.parse('3 * x + 2')
1208 node1.traverse(
1209 (node: math.MathNode, _path: string, _parent: math.MathNode) => {
1210 switch (node.type) {
1211 case 'OperatorNode':
1212 return node.type === 'OperatorNode'
1213 case 'ConstantNode':
1214 return node.type === 'ConstantNode'
1215 case 'SymbolNode':
1216 return node.type === 'SymbolNode'
1217 default:
1218 return
1219 }
1220 }
1221 )
1222}
1223
1224/*
1225Function ceil examples
1226*/
1227{
1228 const math = create(all, {})
1229
1230 // number input
1231 assert.strictEqual(math.ceil(3.2), 4)
1232 assert.strictEqual(math.ceil(-4.2), -4)
1233
1234 // number input
1235 // roundoff result to 2 decimals
1236 assert.strictEqual(math.ceil(3.212, 2), 3.22)
1237 assert.deepStrictEqual(
1238 math.ceil(3.212, math.bignumber(2)),
1239 math.bignumber(3.22)
1240 )
1241 assert.strictEqual(math.ceil(-4.212, 2), -4.21)
1242
1243 // bignumber input
1244 assert.deepStrictEqual(math.ceil(math.bignumber(3.212)), math.bignumber(4))
1245 assert.deepStrictEqual(
1246 math.ceil(math.bignumber(3.212), 2),
1247 math.bignumber(3.22)
1248 )
1249 assert.deepStrictEqual(
1250 math.ceil(math.bignumber(3.212), math.bignumber(2)),
1251 math.bignumber(3.22)
1252 )
1253
1254 // fraction input
1255 assert.deepStrictEqual(math.ceil(math.fraction(44, 7)), math.fraction(7))
1256 assert.deepStrictEqual(math.ceil(math.fraction(-44, 7)), math.fraction(-6))
1257 assert.deepStrictEqual(
1258 math.ceil(math.fraction(44, 7), 2),
1259 math.fraction(629, 100)
1260 )
1261 assert.deepStrictEqual(
1262 math.ceil(math.fraction(44, 7), math.bignumber(2)),
1263 math.fraction(629, 100)
1264 )
1265
1266 // Complex input
1267 const c = math.complex(3.24, -2.71)
1268 assert.deepStrictEqual(math.ceil(c), math.complex(4, -2))
1269 assert.deepStrictEqual(math.ceil(c, 1), math.complex(3.3, -2.7))
1270 assert.deepStrictEqual(
1271 math.ceil(c, math.bignumber(1)),
1272 math.complex(3.3, -2.7)
1273 )
1274
1275 // array input
1276 assert.deepStrictEqual(math.ceil([3.2, 3.8, -4.7]), [4, 4, -4])
1277 assert.deepStrictEqual(math.ceil([3.21, 3.82, -4.71], 1), [3.3, 3.9, -4.7])
1278 assert.deepStrictEqual(
1279 math.ceil([3.21, 3.82, -4.71], math.bignumber(1)),
1280 math.bignumber([3.3, 3.9, -4.7])
1281 )
1282
1283 // numeric input, array or matrix of decimals
1284 const numCeiled: math.MathArray = math.ceil(math.tau, [2, 3])
1285 assert.deepStrictEqual(numCeiled, [6.29, 6.284])
1286 const bigCeiled: math.Matrix = math.ceil(
1287 math.bignumber(6.28318),
1288 math.matrix([2, 3])
1289 )
1290 assert.deepStrictEqual(bigCeiled, math.matrix(math.bignumber([6.29, 6.284])))
1291 assert.deepStrictEqual(math.ceil(math.fraction(44, 7), [2, 3]), [
1292 math.fraction(629, 100),
1293 math.fraction(6286, 1000),
1294 ])
1295
1296 // @ts-expect-error ... verify ceil(array, array) throws an error (for now)
1297 assert.throws(() => math.ceil([3.21, 3.82], [1, 2]), TypeError)
1298}
1299
1300/*
1301Function fix examples
1302*/
1303{
1304 const math = create(all, {})
1305
1306 // number input
1307 assert.strictEqual(math.fix(3.2), 3)
1308 assert.strictEqual(math.fix(-4.2), -4)
1309
1310 // number input
1311 // roundoff result to 2 decimals
1312 assert.strictEqual(math.fix(3.212, 2), 3.21)
1313 assert.deepStrictEqual(
1314 math.fix(3.212, math.bignumber(2)),
1315 math.bignumber(3.21)
1316 )
1317 assert.strictEqual(math.fix(-4.212, 2), -4.21)
1318
1319 // bignumber input
1320 assert.deepStrictEqual(math.fix(math.bignumber(3.212)), math.bignumber(3))
1321 assert.deepStrictEqual(
1322 math.fix(math.bignumber(3.212), 2),
1323 math.bignumber(3.21)
1324 )
1325 assert.deepStrictEqual(
1326 math.fix(math.bignumber(3.212), math.bignumber(2)),
1327 math.bignumber(3.21)
1328 )
1329
1330 // fraction input
1331 assert.deepStrictEqual(math.fix(math.fraction(44, 7)), math.fraction(6))
1332 assert.deepStrictEqual(math.fix(math.fraction(-44, 7)), math.fraction(-6))
1333 assert.deepStrictEqual(
1334 math.fix(math.fraction(44, 7), 2),
1335 math.fraction(628, 100)
1336 )
1337 assert.deepStrictEqual(
1338 math.fix(math.fraction(44, 7), math.bignumber(2)),
1339 math.fraction(628, 100)
1340 )
1341
1342 // Complex input
1343 const c = math.complex(3.24, -2.71)
1344 assert.deepStrictEqual(math.fix(c), math.complex(3, -2))
1345 assert.deepStrictEqual(math.fix(c, 1), math.complex(3.2, -2.7))
1346 assert.deepStrictEqual(
1347 math.fix(c, math.bignumber(1)),
1348 math.complex(3.2, -2.7)
1349 )
1350
1351 // array input
1352 assert.deepStrictEqual(math.fix([3.2, 3.8, -4.7]), [3, 3, -4])
1353 assert.deepStrictEqual(math.fix([3.21, 3.82, -4.71], 1), [3.2, 3.8, -4.7])
1354 assert.deepStrictEqual(
1355 math.fix([3.21, 3.82, -4.71], math.bignumber(1)),
1356 math.bignumber([3.2, 3.8, -4.7])
1357 )
1358
1359 // numeric input, array or matrix of decimals
1360 const numFixed: math.MathArray = math.fix(math.tau, [2, 3])
1361 assert.deepStrictEqual(numFixed, [6.28, 6.283])
1362 const bigFixed: math.Matrix = math.fix(
1363 math.bignumber(6.28318),
1364 math.matrix([2, 3])
1365 )
1366 assert.deepStrictEqual(bigFixed, math.matrix(math.bignumber([6.28, 6.283])))
1367 assert.deepStrictEqual(math.fix(math.fraction(44, 7), [2, 3]), [
1368 math.fraction(628, 100),
1369 math.fraction(6285, 1000),
1370 ])
1371
1372 // @ts-expect-error ... verify fix(array, array) throws an error (for now)
1373 assert.throws(() => math.fix([3.21, 3.82], [1, 2]), TypeError)
1374}
1375
1376/*
1377Function floor examples
1378*/
1379{
1380 const math = create(all, {})
1381
1382 // number input
1383 assert.strictEqual(math.floor(3.2), 3)
1384 assert.strictEqual(math.floor(-4.2), -5)
1385
1386 // number input
1387 // roundoff result to 2 decimals
1388 assert.strictEqual(math.floor(3.212, 2), 3.21)
1389 assert.deepStrictEqual(
1390 math.floor(3.212, math.bignumber(2)),
1391 math.bignumber(3.21)
1392 )
1393 assert.strictEqual(math.floor(-4.212, 2), -4.22)
1394
1395 // bignumber input
1396 assert.deepStrictEqual(math.floor(math.bignumber(3.212)), math.bignumber(3))
1397 assert.deepStrictEqual(
1398 math.floor(math.bignumber(3.212), 2),
1399 math.bignumber(3.21)
1400 )
1401 assert.deepStrictEqual(
1402 math.floor(math.bignumber(3.212), math.bignumber(2)),
1403 math.bignumber(3.21)
1404 )
1405
1406 // fraction input
1407 assert.deepStrictEqual(math.floor(math.fraction(44, 7)), math.fraction(6))
1408 assert.deepStrictEqual(math.floor(math.fraction(-44, 7)), math.fraction(-7))
1409 assert.deepStrictEqual(
1410 math.floor(math.fraction(44, 7), 2),
1411 math.fraction(628, 100)
1412 )
1413 assert.deepStrictEqual(
1414 math.floor(math.fraction(44, 7), math.bignumber(2)),
1415 math.fraction(628, 100)
1416 )
1417
1418 // Complex input
1419 const c = math.complex(3.24, -2.71)
1420 assert.deepStrictEqual(math.floor(c), math.complex(3, -3))
1421 assert.deepStrictEqual(math.floor(c, 1), math.complex(3.2, -2.8))
1422 assert.deepStrictEqual(
1423 math.floor(c, math.bignumber(1)),
1424 math.complex(3.2, -2.8)
1425 )
1426
1427 // array input
1428 assert.deepStrictEqual(math.floor([3.2, 3.8, -4.7]), [3, 3, -5])
1429 assert.deepStrictEqual(math.floor([3.21, 3.82, -4.71], 1), [3.2, 3.8, -4.8])
1430 assert.deepStrictEqual(
1431 math.floor([3.21, 3.82, -4.71], math.bignumber(1)),
1432 math.bignumber([3.2, 3.8, -4.8])
1433 )
1434
1435 // numeric input, array or matrix of decimals
1436 const numFloored: math.MathArray = math.floor(math.tau, [2, 3])
1437 assert.deepStrictEqual(numFloored, [6.28, 6.283])
1438 const bigFloored: math.Matrix = math.floor(
1439 math.bignumber(6.28318),
1440 math.matrix([2, 3])
1441 )
1442 assert.deepStrictEqual(bigFloored, math.matrix(math.bignumber([6.28, 6.283])))
1443 assert.deepStrictEqual(math.floor(math.fraction(44, 7), [2, 3]), [
1444 math.fraction(628, 100),
1445 math.fraction(6285, 1000),
1446 ])
1447
1448 // @ts-expect-error ... verify floor(array, array) throws an error (for now)
1449 assert.throws(() => math.floor([3.21, 3.82], [1, 2]), TypeError)
1450}
1451
1452/*
1453Function round examples
1454*/
1455{
1456 const math = create(all, {})
1457
1458 // number input
1459 assert.strictEqual(math.round(3.2), 3)
1460 assert.strictEqual(math.round(-4.2), -4)
1461
1462 // number input
1463 // roundoff result to 2 decimals
1464 assert.strictEqual(math.round(3.212, 2), 3.21)
1465 assert.deepStrictEqual(
1466 math.round(3.212, math.bignumber(2)),
1467 math.bignumber(3.21)
1468 )
1469 assert.strictEqual(math.round(-4.212, 2), -4.21)
1470
1471 // bignumber input
1472 assert.deepStrictEqual(math.round(math.bignumber(3.212)), math.bignumber(3))
1473 assert.deepStrictEqual(
1474 math.round(math.bignumber(3.212), 2),
1475 math.bignumber(3.21)
1476 )
1477 assert.deepStrictEqual(
1478 math.round(math.bignumber(3.212), math.bignumber(2)),
1479 math.bignumber(3.21)
1480 )
1481
1482 // fraction input
1483 assert.deepStrictEqual(math.round(math.fraction(44, 7)), math.fraction(6))
1484 assert.deepStrictEqual(math.round(math.fraction(-44, 7)), math.fraction(-6))
1485 assert.deepStrictEqual(
1486 math.round(math.fraction(44, 7), 2),
1487 math.fraction(629, 100)
1488 )
1489 assert.deepStrictEqual(
1490 math.round(math.fraction(44, 7), math.bignumber(2)),
1491 math.fraction(629, 100)
1492 )
1493
1494 // Complex input
1495 const c = math.complex(3.24, -2.71)
1496 assert.deepStrictEqual(math.round(c), math.complex(3, -3))
1497 assert.deepStrictEqual(math.round(c, 1), math.complex(3.2, -2.7))
1498 assert.deepStrictEqual(
1499 math.round(c, math.bignumber(1)),
1500 math.complex(3.2, -2.7)
1501 )
1502
1503 // array input
1504 assert.deepStrictEqual(math.round([3.2, 3.8, -4.7]), [3, 4, -5])
1505 assert.deepStrictEqual(math.round([3.21, 3.82, -4.71], 1), [3.2, 3.8, -4.7])
1506 assert.deepStrictEqual(
1507 math.round([3.21, 3.82, -4.71], math.bignumber(1)),
1508 math.bignumber([3.2, 3.8, -4.7])
1509 )
1510
1511 // numeric input, array or matrix of decimals
1512 const numRounded: math.MathArray = math.round(math.tau, [2, 3])
1513 assert.deepStrictEqual(numRounded, [6.28, 6.283])
1514 const bigRounded: math.Matrix = math.round(
1515 math.bignumber(6.28318),
1516 math.matrix([2, 3])
1517 )
1518 assert.deepStrictEqual(bigRounded, math.matrix(math.bignumber([6.28, 6.283])))
1519 assert.deepStrictEqual(math.round(math.fraction(44, 7), [2, 3]), [
1520 math.fraction(629, 100),
1521 math.fraction(6286, 1000),
1522 ])
1523
1524 // @ts-expect-error ... verify round(array, array) throws an error (for now)
1525 assert.throws(() => math.round([3.21, 3.82], [1, 2]), TypeError)
1526}
1527
1528/*
1529 Clone examples
1530 */
1531{
1532 const math = create(all, {})
1533 expectTypeOf(
1534 new math.OperatorNode('/', 'divide', [
1535 new math.ConstantNode(3),
1536 new math.SymbolNode('x'),
1537 ])
1538 ).toMatchTypeOf<OperatorNode<'/', 'divide', (ConstantNode | SymbolNode)[]>>()
1539
1540 expectTypeOf(new math.ConstantNode(1).clone()).toMatchTypeOf<ConstantNode>()
1541 expectTypeOf(
1542 new math.OperatorNode('*', 'multiply', [
1543 new math.ConstantNode(3),
1544 new math.SymbolNode('x'),
1545 ]).clone()
1546 ).toMatchTypeOf<
1547 OperatorNode<'*', 'multiply', (ConstantNode | SymbolNode)[]>
1548 >()
1549
1550 expectTypeOf(
1551 new math.ConstantNode(1).cloneDeep()
1552 ).toMatchTypeOf<ConstantNode>()
1553 expectTypeOf(
1554 new math.OperatorNode('+', 'unaryPlus', [
1555 new math.ConstantNode(3),
1556 new math.SymbolNode('x'),
1557 ]).cloneDeep()
1558 ).toMatchTypeOf<
1559 OperatorNode<'+', 'unaryPlus', (ConstantNode | SymbolNode)[]>
1560 >()
1561
1562 expectTypeOf(
1563 math.clone(new math.ConstantNode(1))
1564 ).toMatchTypeOf<ConstantNode>()
1565}
1566
1567/*
1568JSON serialization/deserialization
1569*/
1570{
1571 const math = create(all, {})
1572
1573 const data = {
1574 bigNumber: math.bignumber('1.5'),
1575 }
1576 const stringified = JSON.stringify(data)
1577 const parsed = JSON.parse(stringified, math.reviver)
1578 assert.deepStrictEqual(parsed.bigNumber, math.bignumber('1.5'))
1579}
1580
1581/*
1582Extend functionality with import
1583 */
1584
1585declare module 'mathjs' {
1586 interface MathJsStatic {
1587 testFun(): number
1588 value: number
1589 }
1590}
1591
1592{
1593 const math = create(all, {})
1594 const testFun = () => 5
1595
1596 math.import(
1597 {
1598 testFun,
1599 value: 10,
1600 },
1601 {}
1602 )
1603
1604 math.testFun()
1605
1606 expectTypeOf(math.testFun()).toMatchTypeOf<number>()
1607
1608 expectTypeOf(
1609 math.import({
1610 myvalue: 42,
1611 myFunc: (name: string) => `myFunc ${name}`,
1612 })
1613 ).toMatchTypeOf<void>()
1614
1615 expectTypeOf(
1616 math.import(
1617 {
1618 myvalue: 42,
1619 myFunc: (name: string) => `myFunc ${name}`,
1620 },
1621 {
1622 override: true,
1623 }
1624 )
1625 ).toMatchTypeOf<void>()
1626
1627 expectTypeOf(
1628 math.import(
1629 {
1630 myvalue2: 42,
1631 },
1632 {
1633 silent: true,
1634 }
1635 )
1636 ).toMatchTypeOf<void>()
1637
1638 expectTypeOf(
1639 math.import(
1640 {
1641 myvalue3: 42,
1642 },
1643 {
1644 wrap: true,
1645 }
1646 )
1647 ).toMatchTypeOf<void>()
1648
1649 expectTypeOf(
1650 math.import({
1651 myvalue4: 42,
1652 })
1653 ).toMatchTypeOf<void>()
1654
1655 expectTypeOf(
1656 math.import([
1657 {
1658 myvalue5: 42,
1659 },
1660 {
1661 myFunc2: (name: string) => `myFunc2 ${name}`,
1662 },
1663 ])
1664 ).toMatchTypeOf<void>()
1665}
1666
1667/*
1668Renamed functions from v5 => v6
1669 */
1670{
1671 const math = create(all, {})
1672 math.typeOf(1)
1673 math.variance([1, 2, 3, 4])
1674 math.evaluate('1 + 2')
1675
1676 // chained operations
1677 math.chain(3).typeOf().done()
1678 math.chain([1, 2, 3]).variance().done()
1679 math.chain('1 + 2').evaluate().done()
1680}
1681
1682/*
1683Factory Test
1684 */
1685{
1686 // create a factory function
1687 const name = 'negativeSquare'
1688 const dependencies: MathJsFunctionName[] = ['multiply', 'unaryMinus']
1689 const createNegativeSquare = factory(name, dependencies, (injected) => {
1690 const { multiply, unaryMinus } = injected
1691 return function negativeSquare(x: number): number {
1692 return unaryMinus(multiply(x, x))
1693 }
1694 })
1695
1696 // create an instance of the function yourself:
1697 const multiply = (a: number, b: number) => a * b
1698 const unaryMinus = (a: number) => -a
1699 const negativeSquare = createNegativeSquare({ multiply, unaryMinus })
1700 negativeSquare(3)
1701}
1702
1703/**
1704 * Dependency map typing test from mathjs official document:
1705 * https://mathjs.org/docs/custom_bundling.html#using-just-a-few-functions
1706 */
1707{
1708 const config = {
1709 // optionally, you can specify configuration
1710 }
1711
1712 // Create just the functions we need
1713 const { fraction, add, divide, format } = create(
1714 {
1715 fractionDependencies,
1716 addDependencies,
1717 divideDependencies,
1718 formatDependencies,
1719 },
1720 config
1721 )
1722
1723 // Use the created functions
1724 const a = fraction(1, 3)
1725 const b = fraction(3, 7)
1726 const c = add(a, b)
1727 const d = divide(a, b)
1728 assert.strictEqual(format(c), '16/21')
1729 assert.strictEqual(format(d), '7/9')
1730}
1731
1732/**
1733 * Custom parsing functions
1734 * https://mathjs.org/docs/expressions/customization.html#customize-supported-characters
1735 */
1736{
1737 const math = create(all, {})
1738 const isAlphaOriginal = math.parse.isAlpha
1739 math.parse.isAlpha = (c, cPrev, cNext) => {
1740 return isAlphaOriginal(c, cPrev, cNext) || c === '\u260E'
1741 }
1742
1743 // now we can use the \u260E (phone) character in expressions
1744 const result = math.evaluate('\u260Efoo', { '\u260Efoo': 42 })
1745 assert.strictEqual(result, 42)
1746}
1747
1748/**
1749 * Util functions
1750 * https://mathjs.org/docs/reference/functions.html#utils-functions
1751 */
1752{
1753 const math = create(all, {})
1754
1755 // hasNumericValue function
1756 assert.strictEqual(math.hasNumericValue(2), true)
1757 assert.strictEqual(math.hasNumericValue('2'), true)
1758 assert.strictEqual(math.isNumeric('2'), false)
1759 assert.strictEqual(math.hasNumericValue(0), true)
1760 assert.strictEqual(math.hasNumericValue(math.bignumber(500)), true)
1761 assert.deepStrictEqual(math.hasNumericValue([2.3, 'foo', false]), [
1762 true,
1763 false,
1764 true,
1765 ])
1766 assert.strictEqual(math.hasNumericValue(math.fraction(4)), true)
1767 assert.strictEqual(math.hasNumericValue(math.complex('2-4i')), false)
1768}
1769
1770/**
1771 * src/util/is functions
1772 */
1773{
1774 const math = create(all, {})
1775
1776 type IsFunc = (x: unknown) => boolean
1777 const isFuncs: IsFunc[] = [
1778 math.isNumber,
1779 math.isBigNumber,
1780 math.isComplex,
1781 math.isFraction,
1782 math.isUnit,
1783 math.isString,
1784 math.isArray,
1785 math.isMatrix,
1786 math.isCollection,
1787 math.isDenseMatrix,
1788 math.isSparseMatrix,
1789 math.isRange,
1790 math.isIndex,
1791 math.isBoolean,
1792 math.isResultSet,
1793 math.isHelp,
1794 math.isFunction,
1795 math.isDate,
1796 math.isRegExp,
1797 math.isObject,
1798 math.isNull,
1799 math.isUndefined,
1800 math.isAccessorNode,
1801 math.isArrayNode,
1802 math.isAssignmentNode,
1803 math.isBlockNode,
1804 math.isConditionalNode,
1805 math.isConstantNode,
1806 math.isFunctionAssignmentNode,
1807 math.isFunctionNode,
1808 math.isIndexNode,
1809 math.isNode,
1810 math.isObjectNode,
1811 math.isOperatorNode,
1812 math.isParenthesisNode,
1813 math.isRangeNode,
1814 math.isSymbolNode,
1815 math.isChain,
1816 ]
1817
1818 isFuncs.forEach((f) => {
1819 const result = f(1)
1820 const isResultBoolean = result === true || result === false
1821 assert.ok(isResultBoolean)
1822 })
1823
1824 // Check guards do type refinement
1825
1826 let x: unknown
1827
1828 if (math.isNumber(x)) {
1829 expectTypeOf(x).toMatchTypeOf<number>()
1830 }
1831 if (math.isBigNumber(x)) {
1832 expectTypeOf(x).toMatchTypeOf<math.BigNumber>()
1833 }
1834 if (math.isComplex(x)) {
1835 expectTypeOf(x).toMatchTypeOf<math.Complex>()
1836 }
1837 if (math.isFraction(x)) {
1838 expectTypeOf(x).toMatchTypeOf<math.Fraction>()
1839 }
1840 if (math.isUnit(x)) {
1841 expectTypeOf(x).toMatchTypeOf<math.Unit>()
1842 }
1843 if (math.isString(x)) {
1844 expectTypeOf(x).toMatchTypeOf<string>()
1845 }
1846 if (math.isArray(x)) {
1847 expectTypeOf(x).toMatchTypeOf<unknown[]>()
1848 }
1849 if (math.isMatrix(x)) {
1850 expectTypeOf(x).toMatchTypeOf<math.Matrix>()
1851 }
1852 if (math.isDenseMatrix(x)) {
1853 expectTypeOf(x).toMatchTypeOf<math.Matrix>()
1854 }
1855 if (math.isSparseMatrix(x)) {
1856 expectTypeOf(x).toMatchTypeOf<math.Matrix>()
1857 }
1858 if (math.isIndex(x)) {
1859 expectTypeOf(x).toMatchTypeOf<math.Index>()
1860 }
1861 if (math.isBoolean(x)) {
1862 expectTypeOf(x).toMatchTypeOf<boolean>()
1863 }
1864 if (math.isHelp(x)) {
1865 expectTypeOf(x).toMatchTypeOf<math.Help>()
1866 }
1867 if (math.isDate(x)) {
1868 expectTypeOf(x).toMatchTypeOf<Date>()
1869 }
1870 if (math.isRegExp(x)) {
1871 expectTypeOf(x).toMatchTypeOf<RegExp>()
1872 }
1873 if (math.isNull(x)) {
1874 expectTypeOf(x).toMatchTypeOf<null>()
1875 }
1876 if (math.isUndefined(x)) {
1877 expectTypeOf(x).toMatchTypeOf<undefined>()
1878 }
1879
1880 if (math.isAccessorNode(x)) {
1881 expectTypeOf(x).toMatchTypeOf<math.AccessorNode>()
1882 }
1883 if (math.isArrayNode(x)) {
1884 expectTypeOf(x).toMatchTypeOf<math.ArrayNode>()
1885 }
1886 if (math.isAssignmentNode(x)) {
1887 expectTypeOf(x).toMatchTypeOf<math.AssignmentNode>()
1888 }
1889 if (math.isBlockNode(x)) {
1890 expectTypeOf(x).toMatchTypeOf<math.BlockNode>()
1891 }
1892 if (math.isConditionalNode(x)) {
1893 expectTypeOf(x).toMatchTypeOf<math.ConditionalNode>()
1894 }
1895 if (math.isConstantNode(x)) {
1896 expectTypeOf(x).toMatchTypeOf<math.ConstantNode>()
1897 }
1898 if (math.isFunctionAssignmentNode(x)) {
1899 expectTypeOf(x).toMatchTypeOf<math.FunctionAssignmentNode>()
1900 }
1901 if (math.isFunctionNode(x)) {
1902 expectTypeOf(x).toMatchTypeOf<math.FunctionNode>()
1903 }
1904 if (math.isIndexNode(x)) {
1905 expectTypeOf(x).toMatchTypeOf<math.IndexNode>()
1906 }
1907 if (math.isNode(x)) {
1908 expectTypeOf(x).toMatchTypeOf<math.MathNodeCommon>()
1909 }
1910 if (math.isNode(x)) {
1911 expectTypeOf(x).toMatchTypeOf<math.MathNodeCommon>()
1912 }
1913 if (math.isObjectNode(x)) {
1914 expectTypeOf(x).toMatchTypeOf<math.ObjectNode>()
1915 }
1916 if (math.isOperatorNode(x)) {
1917 expectTypeOf(x).toMatchTypeOf<
1918 OperatorNode<OperatorNodeOp, OperatorNodeFn, MathNode[]>
1919 >()
1920 }
1921 if (math.isParenthesisNode(x)) {
1922 expectTypeOf(x).toMatchTypeOf<math.ParenthesisNode>()
1923 }
1924 if (math.isRangeNode(x)) {
1925 expectTypeOf(x).toMatchTypeOf<math.RangeNode>()
1926 }
1927 if (math.isSymbolNode(x)) {
1928 expectTypeOf(x).toMatchTypeOf<math.SymbolNode>()
1929 }
1930 if (math.isChain(x)) {
1931 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1932 expectTypeOf(x).toMatchTypeOf<math.MathJsChain<any>>()
1933 }
1934}
1935
1936/*
1937Probability function examples
1938*/
1939{
1940 const math = create(all, {})
1941
1942 expectTypeOf(math.lgamma(1.5)).toMatchTypeOf<number>()
1943 expectTypeOf(
1944 math.lgamma(math.complex(1.5, -1.5))
1945 ).toMatchTypeOf<math.Complex>()
1946}
1947
1948/*
1949toTex examples
1950*/
1951
1952{
1953 const math = create(all, {})
1954
1955 expectTypeOf(math.parse('a/b').toTex()).toMatchTypeOf<string>()
1956
1957 // TODO add proper types for toTex options
1958 expectTypeOf(
1959 math.parse('a/b').toTex({
1960 a: '123',
1961 })
1962 ).toMatchTypeOf<string>()
1963}
1964
1965/*
1966Resolve examples
1967*/
1968{
1969 const math = create(all, {})
1970
1971 expectTypeOf(math.resolve(math.parse('x + y'))).toMatchTypeOf<MathNode>()
1972 expectTypeOf(
1973 math.resolve(math.parse('x + y'), { x: 0 })
1974 ).toMatchTypeOf<MathNode>()
1975 expectTypeOf(math.resolve([math.parse('x + y')], { x: 0 })).toMatchTypeOf<
1976 MathNode[]
1977 >()
1978}