UNPKG

14.6 kBPlain TextView Raw
1import {
2 create,
3 factory,
4 all,
5 MathJsFunctionName,
6 fractionDependencies,
7 addDependencies,
8 divideDependencies,
9 formatDependencies,
10} from 'mathjs';
11
12/*
13Basic usage examples
14*/
15{
16 const math = create(all);
17
18 // functions and constants
19 math.round(math.e, 3);
20 math.round(100.123, 3);
21 math.atan2(3, -3) / math.pi;
22 math.log(10000, 10);
23 math.sqrt(-4);
24 math.pow([[-1, 2], [3, 1]], 2);
25 const angle = 0.2;
26 math.add(math.pow(math.sin(angle), 2), math.pow(math.cos(angle), 2));
27
28 // expressions
29 math.evaluate('1.2 * (2 + 4.5)');
30
31 // chained operations
32 const a = math.chain(3).add(4).multiply(2).done(); // 14
33
34 // mixed use of different data types in functions
35 math.add(4, [5, 6]); // number + Array, [9, 10]
36 math.multiply(math.unit('5 mm'), 3); // Unit * number, 15 mm
37 math.subtract([2, 3, 4], 5); // Array - number, [-3, -2, -1]
38 math.add(math.matrix([2, 3]), [4, 5]); // Matrix + Array, [6, 8]
39}
40
41/*
42Bignumbers examples
43*/
44{
45 // configure the default type of numbers as BigNumbers
46 const math = create(all, {
47 number: 'BigNumber',
48 precision: 20,
49 });
50
51 {
52 math.add(math.bignumber(0.1), math.bignumber(0.2)); // BigNumber, 0.3
53 math.divide(math.bignumber(0.3), math.bignumber(0.2)); // BigNumber, 1.5
54 }
55}
56
57/*
58Chaining examples
59*/
60{
61 const math = create(all, {});
62 const a = math.chain(3).add(4).multiply(2).done(); // 14
63
64 // Another example, calculate square(sin(pi / 4))
65 const b = math.chain(math.pi).divide(4).sin().square().done();
66
67 // toString will return a string representation of the chain's value
68 const chain = math.chain(2).divide(3);
69 const str: string = chain.toString(); // "0.6666666666666666"
70
71 chain.valueOf();
72
73 // the function subset can be used to get or replace sub matrices
74 const array = [
75 [1, 2],
76 [3, 4],
77 ];
78 const v = math.chain(array).subset(math.index(1, 0)).done(); // 3
79
80 const m = math.chain(array).subset(math.index(0, 0), 8).multiply(3).done();
81
82 // filtering
83 math
84 .chain([-1, 0, 1.1, 2, 3, 1000])
85 .filter(math.isPositive)
86 .filter(math.isInteger)
87 .filter((n) => n !== 1000)
88 .done(); // [2, 3]
89}
90
91/*
92Simplify examples
93*/
94{
95 const math = create(all);
96
97 math.simplify("2 * 1 * x ^ (2 - 1)");
98 math.simplify("2 * 3 * x", { x: 4 });
99
100 const f = math.parse("2 * 1 * x ^ (2 - 1)");
101 math.simplify(f);
102
103 math.simplify("0.4 * x", {}, { exactFractions: true });
104 math.simplify("0.4 * x", {}, { exactFractions: false });
105}
106
107/*
108Complex numbers examples
109*/
110{
111 const math = create(all, {});
112 const a = math.complex(2, 3);
113 // create a complex number by providing a string with real and complex parts
114 const b = math.complex('3 - 7i');
115
116 // read the real and complex parts of the complex number
117 {
118 const x: number = a.re;
119 const y: number = a.im;
120
121 // adjust the complex value
122 a.re = 5;
123 }
124
125 // clone a complex value
126 {
127 const clone = a.clone();
128 }
129
130 // perform operations with complex numbers
131 {
132 math.add(a, b);
133 math.multiply(a, b);
134 math.sin(a);
135 }
136
137 // create a complex number from polar coordinates
138 {
139 const p: math.PolarCoordinates = { r: math.sqrt(2), phi: math.pi / 4 };
140 const c: math.Complex = math.complex(p);
141 }
142
143 // get polar coordinates of a complex number
144 {
145 const p: math.PolarCoordinates = math.complex(3, 4).toPolar();
146 }
147}
148
149/*
150Expressions examples
151*/
152{
153 const math = create(all, {});
154 // evaluate expressions
155 {
156 math.evaluate('sqrt(3^2 + 4^2)');
157 }
158
159 // evaluate multiple expressions at once
160 {
161 math.evaluate(['f = 3', 'g = 4', 'f * g']);
162 }
163
164 // get content of a parenthesis node
165 {
166 const node = math.parse('(1)');
167 const innerNode = node.content;
168 }
169
170 // scope can contain both variables and functions
171 {
172 const scope = { hello: (name: string) => `hello, ${name}!` };
173 math.evaluate('hello("hero")', scope); // "hello, hero!"
174 }
175
176 // define a function as an expression
177 {
178 const scope: any = {
179 a: 3,
180 b: 4,
181 };
182 const f = math.evaluate('f(x) = x ^ a', scope);
183 f(2);
184 scope.f(2);
185 }
186
187 {
188 const node2 = math.parse('x^a');
189 const code2: math.EvalFunction = node2.compile();
190 node2.toString();
191 }
192
193 // 3. using function math.compile
194 // parse an expression
195 {
196 // provide a scope for the variable assignment
197 const code2 = math.compile('a = a + 3');
198 const scope = { a: 7 };
199 code2.evaluate(scope);
200 }
201 // 4. using a parser
202 const parser = math.parser();
203
204 // get and set variables and functions
205 {
206 parser.evaluate('x = 7 / 2'); // 3.5
207 parser.evaluate('x + 3'); // 6.5
208 parser.evaluate('f(x, y) = x^y'); // f(x, y)
209 parser.evaluate('f(2, 3)'); // 8
210
211 const x = parser.get('x');
212 const f = parser.get('f');
213 const y = parser.getAll();
214 const g = f(3, 3);
215
216 parser.set('h', 500);
217 parser.set('hello', (name: string) => `hello, ${name}!`);
218 }
219
220 // clear defined functions and variables
221 parser.clear();
222}
223
224/*
225Fractions examples
226*/
227{
228 // configure the default type of numbers as Fractions
229 const math = create(all, {
230 number: 'Fraction',
231 });
232
233 const x = math.fraction(0.125);
234 const y = math.fraction('1/3');
235 math.fraction(2, 3);
236
237 math.add(x, y);
238 math.divide(x, y);
239
240 // output formatting
241 const a = math.fraction('2/3');
242}
243
244/*
245Matrices examples
246*/
247{
248 const math = create(all, {});
249
250 // create matrices and arrays. a matrix is just a wrapper around an Array,
251 // providing some handy utilities.
252 const a: math.Matrix = math.matrix([1, 4, 9, 16, 25]);
253 const b: math.Matrix = math.matrix(math.ones([2, 3]));
254 b.size();
255
256 // the Array data of a Matrix can be retrieved using valueOf()
257 const array = a.valueOf();
258
259 // Matrices can be cloned
260 const clone: math.Matrix = a.clone();
261
262 // perform operations with matrices
263 math.sqrt(a);
264 math.factorial(a);
265
266 // create and manipulate matrices. Arrays and Matrices can be used mixed.
267 {
268 const a = [
269 [1, 2],
270 [3, 4],
271 ];
272 const b: math.Matrix = math.matrix([
273 [5, 6],
274 [1, 1],
275 ]);
276
277 b.subset(math.index(1, [0, 1]), [[7, 8]]);
278 const c = math.multiply(a, b);
279 const f: math.Matrix = math.matrix([1, 0]);
280 const d: math.Matrix = f.subset(math.index(1, 0));
281 }
282
283 // get a sub matrix
284 {
285 const a: math.Matrix = math.diag(math.range(1, 4));
286 a.subset(math.index([1, 2], [1, 2]));
287 const b: math.Matrix = math.range(1, 6);
288 b.subset(math.index(math.range(1, 4)));
289 }
290
291 // resize a multi dimensional matrix
292 {
293 const a = math.matrix();
294 a.resize([2, 2, 2], 0);
295 a.size();
296 a.resize([2, 2]);
297 a.size();
298 }
299
300 // can set a subset of a matrix to uninitialized
301 {
302 const m = math.matrix();
303 m.subset(math.index(2), 6, math.uninitialized);
304 }
305
306 // create ranges
307 {
308 math.range(1, 6);
309 math.range(0, 18, 3);
310 math.range('2:-1:-3');
311 math.factorial(math.range('1:6'));
312 }
313
314 // map matrix
315 {
316 math.map([1, 2, 3], function (value) {
317 return value * value;
318 }); // returns [1, 4, 9]
319 }
320
321 // filter matrix
322 {
323 math.filter([6, -2, -1, 4, 3], function (x) {
324 return x > 0;
325 }); // returns [6, 4, 3]
326 math.filter(['23', 'foo', '100', '55', 'bar'], /[0-9]+/); // returns ["23", "100", "55"]
327 }
328
329 // concat matrix
330 {
331 math.concat([[0, 1, 2]], [[1, 2, 3]]); // returns [[ 0, 1, 2, 1, 2, 3 ]]
332 math.concat([[0, 1, 2]], [[1, 2, 3]], 0); // returns [[ 0, 1, 2 ], [ 1, 2, 3 ]]
333 }
334}
335
336/*
337Sparse matrices examples
338*/
339{
340 const math = create(all, {});
341
342 // create a sparse matrix
343 const a = math.identity(1000, 1000, 'sparse');
344
345 // do operations with a sparse matrix
346 const b = math.multiply(a, a);
347 const c = math.multiply(b, math.complex(2, 2));
348 const d = math.matrix([0, 1]);
349 const e = math.transpose(d);
350 const f = math.multiply(e, a);
351}
352
353/*
354Units examples
355*/
356{
357 const math = create(all, {});
358
359 // units can be created by providing a value and unit name, or by providing
360 // a string with a valued unit.
361 const a = math.unit(45, 'cm'); // 450 mm
362 const b = math.unit('0.1m'); // 100 mm
363
364 // creating units
365 math.createUnit('foo');
366 math.createUnit('furlong', '220 yards');
367 math.createUnit('furlong', '220 yards', { override: true });
368 math.createUnit('testunit', { definition: '0.555556 kelvin', offset: 459.67 });
369 math.createUnit('testunit', { definition: '0.555556 kelvin', offset: 459.67 }, { override: true });
370 math.createUnit('knot', { definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts'] });
371 math.createUnit('knot', { definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts'] }, { override: true });
372 math.createUnit(
373 'knot',
374 {
375 definition: '0.514444 m/s',
376 aliases: ['knots', 'kt', 'kts'],
377 prefixes: 'long',
378 },
379 { override: true }
380 );
381 math.createUnit(
382 {
383 foo_2: {
384 prefixes: 'long',
385 },
386 bar: '40 foo',
387 baz: {
388 definition: '1 bar/hour',
389 prefixes: 'long',
390 },
391 },
392 {
393 override: true,
394 }
395 );
396 // use Unit as definition
397 math.createUnit('c', { definition: b });
398 math.createUnit('c', { definition: b }, { override: true });
399
400 // units can be added, subtracted, and multiplied or divided by numbers and by other units
401 math.add(a, b);
402 math.multiply(b, 2);
403 math.divide(math.unit('1 m'), math.unit('1 s'));
404 math.pow(math.unit('12 in'), 3);
405
406 // units can be converted to a specific type, or to a number
407 b.to('cm');
408 math.to(b, 'inch');
409 b.toNumber('cm');
410 math.number(b, 'cm');
411
412 // the expression parser supports units too
413 math.evaluate('2 inch to cm');
414
415 // units can be converted to SI
416 math.unit('1 inch').toSI();
417
418 // units can be split into other units
419 math.unit('1 m').splitUnit(['ft', 'in']);
420}
421
422/*
423Expression tree examples
424*/
425{
426 const math = create(all, {});
427
428 // Filter an expression tree
429 const node: math.MathNode = math.parse('x^2 + x/4 + 3*y');
430 const filtered: math.MathNode[] = node.filter((node: math.MathNode) => node.isSymbolNode && node.name === 'x');
431
432 const arr: string[] = filtered.map((node: math.MathNode) => node.toString());
433
434 // Traverse an expression tree
435 const node1: math.MathNode = math.parse('3 * x + 2');
436 node1.traverse((node: math.MathNode, path: string, parent: math.MathNode) => {
437 switch (node.type) {
438 case 'OperatorNode':
439 return node.type === 'OperatorNode';
440 case 'ConstantNode':
441 return node.type === 'ConstantNode';
442 case 'SymbolNode':
443 return node.type === 'SymbolNode';
444 default:
445 return node.type === 'any string at all';
446 }
447 });
448}
449
450/*
451Function floor examples
452*/
453{
454 const math = create(all, {});
455
456 // number input
457 math.floor(3.2); // returns number 3
458 math.floor(-4.2); // returns number -5
459
460 // number input
461 // roundoff result to 2 decimals
462 math.floor(3.212, 2); // returns number 3.21
463 math.floor(-4.212, 2); // returns number -4.22
464
465 // Complex input
466 const c = math.complex(3.24, -2.71); // returns Complex 3 - 3i
467 math.floor(c); // returns Complex 3 - 3i
468 math.floor(c, 1); // returns Complex 3.2 - 2.8i
469
470 //array input
471 math.floor([3.2, 3.8, -4.7]); // returns Array [3, 3, -5]
472 math.floor([3.21, 3.82, -4.71], 1); // returns Array [3.2, 3.8, -4.8]
473}
474
475
476/*
477JSON serialization/deserialization
478*/
479{
480 const math = create(all, {});
481
482 const data = {
483 bigNumber: math.bignumber('1.5'),
484 };
485 const stringified = JSON.stringify(data);
486 const parsed = JSON.parse(stringified, math.json.reviver);
487 parsed.bigNumber === math.bignumber('1.5'); // true
488}
489
490/*
491Extend functionality with import
492 */
493
494declare module 'mathjs' {
495 interface MathJsStatic {
496 testFun(): number;
497 value: number;
498 }
499}
500
501{
502 const math = create(all, {});
503 const testFun = () => 5;
504
505 math.import(
506 {
507 testFun,
508 value: 10,
509 },
510 {}
511 );
512
513 math.testFun();
514
515 const a = math.value * 2;
516}
517
518/*
519Renamed functions from v5 => v6
520 */
521{
522 const math = create(all, {});
523 math.typeOf(1);
524 math.variance([1, 2, 3, 4]);
525 math.evaluate('1 + 2');
526
527 // chained operations
528 math.chain(3).typeOf().done();
529 math.chain([1, 2, 3]).variance().done();
530 math.chain('1 + 2').evaluate().done();
531}
532
533/*
534Factory Test
535 */
536{
537 // create a factory function
538 const name = 'negativeSquare';
539 const dependencies: MathJsFunctionName[] = ['multiply', 'unaryMinus'];
540 const createNegativeSquare = factory(name, dependencies, (injected) => {
541 const { multiply, unaryMinus } = injected;
542 return function negativeSquare(x: number): number {
543 return unaryMinus(multiply(x, x));
544 };
545 });
546
547 // create an instance of the function yourself:
548 const multiply = (a: number, b: number) => a * b;
549 const unaryMinus = (a: number) => -a;
550 const negativeSquare = createNegativeSquare({ multiply, unaryMinus });
551 negativeSquare(3);
552}
553
554/**
555 * Dependency map typing test from mathjs official document:
556 * https://mathjs.org/docs/custom_bundling.html#using-just-a-few-functions
557 */
558{
559 const config = {
560 // optionally, you can specify configuration
561 };
562
563 // Create just the functions we need
564 const { fraction, add, divide, format } = create(
565 {
566 fractionDependencies,
567 addDependencies,
568 divideDependencies,
569 formatDependencies,
570 },
571 config
572 );
573
574 // Use the created functions
575 const a = fraction(1, 3);
576 const b = fraction(3, 7);
577 const c = add(a, b);
578 const d = divide(a, b);
579 console.log('c =', format(c)); // outputs "c = 16/21"
580 console.log('d =', format(d)); // outputs "d = 7/9"
581}
582
583/**
584 * Custom parsing functions
585 * https://mathjs.org/docs/expressions/customization.html#customize-supported-characters
586 */
587{
588 const math = create(all, {});
589 const isAlphaOriginal = math.parse.isAlpha;
590 math.parse.isAlpha = (c, cPrev, cNext) => {
591 return isAlphaOriginal(c, cPrev, cNext) || c === "\u260E";
592 };
593
594 // now we can use the \u260E (phone) character in expressions
595 const result = math.evaluate("\u260Efoo", { "\u260Efoo": 42 }); // returns 42
596 console.log(result);
597}
598
599/**
600 * Util functions
601 * https://mathjs.org/docs/reference/functions.html#utils-functions
602 */
603{
604 const math = create(all, {});
605
606 // hasNumericValue function
607 math.hasNumericValue(2); // returns true
608 math.hasNumericValue('2'); // returns true
609 math.isNumeric('2'); // returns false
610 math.hasNumericValue(0); // returns true
611 math.hasNumericValue(math.bignumber(500)); // returns true
612 math.hasNumericValue([2.3, 'foo', false]); // returns [true, false, true]
613 math.hasNumericValue(math.fraction(4)); // returns true
614 math.hasNumericValue(math.complex('2-4i')); // returns false
615}
616