UNPKG

12.9 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/*
92Complex numbers examples
93*/
94{
95 const math = create(all, {});
96 const a = math.complex(2, 3);
97 // create a complex number by providing a string with real and complex parts
98 const b = math.complex('3 - 7i');
99
100 // read the real and complex parts of the complex number
101 {
102 const x: number = a.re;
103 const y: number = a.im;
104
105 // adjust the complex value
106 a.re = 5;
107 }
108
109 // clone a complex value
110 {
111 const clone = a.clone();
112 }
113
114 // perform operations with complex numbers
115 {
116 math.add(a, b);
117 math.multiply(a, b);
118 math.sin(a);
119 }
120
121 // create a complex number from polar coordinates
122 {
123 const p: math.PolarCoordinates = { r: math.sqrt(2), phi: math.pi / 4 };
124 const c: math.Complex = math.complex(p);
125 }
126
127 // get polar coordinates of a complex number
128 {
129 const p: math.PolarCoordinates = math.complex(3, 4).toPolar();
130 }
131}
132
133/*
134Expressions examples
135*/
136{
137 const math = create(all, {});
138 // evaluate expressions
139 {
140 math.evaluate('sqrt(3^2 + 4^2)');
141 }
142
143 // evaluate multiple expressions at once
144 {
145 math.evaluate(['f = 3', 'g = 4', 'f * g']);
146 }
147
148 // get content of a parenthesis node
149 {
150 const node = math.parse('(1)');
151 const innerNode = node.content;
152 }
153
154 // scope can contain both variables and functions
155 {
156 const scope = { hello: (name: string) => `hello, ${name}!` };
157 math.evaluate('hello("hero")', scope); // "hello, hero!"
158 }
159
160 // define a function as an expression
161 {
162 const scope: any = {
163 a: 3,
164 b: 4,
165 };
166 const f = math.evaluate('f(x) = x ^ a', scope);
167 f(2);
168 scope.f(2);
169 }
170
171 {
172 const node2 = math.parse('x^a');
173 const code2: math.EvalFunction = node2.compile();
174 node2.toString();
175 }
176
177 // 3. using function math.compile
178 // parse an expression
179 {
180 // provide a scope for the variable assignment
181 const code2 = math.compile('a = a + 3');
182 const scope = { a: 7 };
183 code2.evaluate(scope);
184 }
185 // 4. using a parser
186 const parser = math.parser();
187
188 // get and set variables and functions
189 {
190 parser.evaluate('x = 7 / 2'); // 3.5
191 parser.evaluate('x + 3'); // 6.5
192 parser.evaluate('f(x, y) = x^y'); // f(x, y)
193 parser.evaluate('f(2, 3)'); // 8
194
195 const x = parser.get('x');
196 const f = parser.get('f');
197 const y = parser.getAll();
198 const g = f(3, 3);
199
200 parser.set('h', 500);
201 parser.set('hello', (name: string) => `hello, ${name}!`);
202 }
203
204 // clear defined functions and variables
205 parser.clear();
206}
207
208/*
209Fractions examples
210*/
211{
212 // configure the default type of numbers as Fractions
213 const math = create(all, {
214 number: 'Fraction',
215 });
216
217 const x = math.fraction(0.125);
218 const y = math.fraction('1/3');
219 math.fraction(2, 3);
220
221 math.add(x, y);
222 math.divide(x, y);
223
224 // output formatting
225 const a = math.fraction('2/3');
226}
227
228/*
229Matrices examples
230*/
231{
232 const math = create(all, {});
233
234 // create matrices and arrays. a matrix is just a wrapper around an Array,
235 // providing some handy utilities.
236 const a: math.Matrix = math.matrix([1, 4, 9, 16, 25]);
237 const b: math.Matrix = math.matrix(math.ones([2, 3]));
238 b.size();
239
240 // the Array data of a Matrix can be retrieved using valueOf()
241 const array = a.valueOf();
242
243 // Matrices can be cloned
244 const clone: math.Matrix = a.clone();
245
246 // perform operations with matrices
247 math.sqrt(a);
248 math.factorial(a);
249
250 // create and manipulate matrices. Arrays and Matrices can be used mixed.
251 {
252 const a = [
253 [1, 2],
254 [3, 4],
255 ];
256 const b: math.Matrix = math.matrix([
257 [5, 6],
258 [1, 1],
259 ]);
260
261 b.subset(math.index(1, [0, 1]), [[7, 8]]);
262 const c = math.multiply(a, b);
263 const f: math.Matrix = math.matrix([1, 0]);
264 const d: math.Matrix = f.subset(math.index(1, 0));
265 }
266
267 // get a sub matrix
268 {
269 const a: math.Matrix = math.diag(math.range(1, 4));
270 a.subset(math.index([1, 2], [1, 2]));
271 const b: math.Matrix = math.range(1, 6);
272 b.subset(math.index(math.range(1, 4)));
273 }
274
275 // resize a multi dimensional matrix
276 {
277 const a = math.matrix();
278 a.resize([2, 2, 2], 0);
279 a.size();
280 a.resize([2, 2]);
281 a.size();
282 }
283
284 // can set a subset of a matrix to uninitialized
285 {
286 const m = math.matrix();
287 m.subset(math.index(2), 6, math.uninitialized);
288 }
289
290 // create ranges
291 {
292 math.range(1, 6);
293 math.range(0, 18, 3);
294 math.range('2:-1:-3');
295 math.factorial(math.range('1:6'));
296 }
297
298 // map matrix
299 {
300 math.map([1, 2, 3], function (value) {
301 return value * value;
302 }); // returns [1, 4, 9]
303 }
304
305 // filter matrix
306 {
307 math.filter([6, -2, -1, 4, 3], function (x) {
308 return x > 0;
309 }); // returns [6, 4, 3]
310 math.filter(['23', 'foo', '100', '55', 'bar'], /[0-9]+/); // returns ["23", "100", "55"]
311 }
312
313 // concat matrix
314 {
315 math.concat([[0, 1, 2]], [[1, 2, 3]]); // returns [[ 0, 1, 2, 1, 2, 3 ]]
316 math.concat([[0, 1, 2]], [[1, 2, 3]], 0); // returns [[ 0, 1, 2 ], [ 1, 2, 3 ]]
317 }
318}
319
320/*
321Sparse matrices examples
322*/
323{
324 const math = create(all, {});
325
326 // create a sparse matrix
327 const a = math.identity(1000, 1000, 'sparse');
328
329 // do operations with a sparse matrix
330 const b = math.multiply(a, a);
331 const c = math.multiply(b, math.complex(2, 2));
332 const d = math.matrix([0, 1]);
333 const e = math.transpose(d);
334 const f = math.multiply(e, a);
335}
336
337/*
338Units examples
339*/
340{
341 const math = create(all, {});
342
343 // units can be created by providing a value and unit name, or by providing
344 // a string with a valued unit.
345 const a = math.unit(45, 'cm'); // 450 mm
346 const b = math.unit('0.1m'); // 100 mm
347
348 // creating units
349 math.createUnit('foo');
350 math.createUnit('furlong', '220 yards');
351 math.createUnit('furlong', '220 yards', { override: true });
352 math.createUnit('testunit', { definition: '0.555556 kelvin', offset: 459.67 });
353 math.createUnit('testunit', { definition: '0.555556 kelvin', offset: 459.67 }, { override: true });
354 math.createUnit('knot', { definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts'] });
355 math.createUnit('knot', { definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts'] }, { override: true });
356 math.createUnit(
357 'knot',
358 {
359 definition: '0.514444 m/s',
360 aliases: ['knots', 'kt', 'kts'],
361 prefixes: 'long',
362 },
363 { override: true }
364 );
365 math.createUnit(
366 {
367 foo_2: {
368 prefixes: 'long',
369 },
370 bar: '40 foo',
371 baz: {
372 definition: '1 bar/hour',
373 prefixes: 'long',
374 },
375 },
376 {
377 override: true,
378 }
379 );
380 // use Unit as definition
381 math.createUnit('c', { definition: b });
382 math.createUnit('c', { definition: b }, { override: true });
383
384 // units can be added, subtracted, and multiplied or divided by numbers and by other units
385 math.add(a, b);
386 math.multiply(b, 2);
387 math.divide(math.unit('1 m'), math.unit('1 s'));
388 math.pow(math.unit('12 in'), 3);
389
390 // units can be converted to a specific type, or to a number
391 b.to('cm');
392 math.to(b, 'inch');
393 b.toNumber('cm');
394 math.number(b, 'cm');
395
396 // the expression parser supports units too
397 math.evaluate('2 inch to cm');
398
399 // units can be converted to SI
400 math.unit('1 inch').toSI();
401
402 // units can be split into other units
403 math.unit('1 m').splitUnit(['ft', 'in']);
404}
405
406/*
407Expression tree examples
408*/
409{
410 const math = create(all, {});
411
412 // Filter an expression tree
413 const node: math.MathNode = math.parse('x^2 + x/4 + 3*y');
414 const filtered: math.MathNode[] = node.filter((node: math.MathNode) => node.isSymbolNode && node.name === 'x');
415
416 const arr: string[] = filtered.map((node: math.MathNode) => node.toString());
417
418 // Traverse an expression tree
419 const node1: math.MathNode = math.parse('3 * x + 2');
420 node1.traverse((node: math.MathNode, path: string, parent: math.MathNode) => {
421 switch (node.type) {
422 case 'OperatorNode':
423 return node.type === 'OperatorNode';
424 case 'ConstantNode':
425 return node.type === 'ConstantNode';
426 case 'SymbolNode':
427 return node.type === 'SymbolNode';
428 default:
429 return node.type === 'any string at all';
430 }
431 });
432}
433
434/*
435JSON serialization/deserialization
436*/
437{
438 const math = create(all, {});
439
440 const data = {
441 bigNumber: math.bignumber('1.5'),
442 };
443 const stringified = JSON.stringify(data);
444 const parsed = JSON.parse(stringified, math.json.reviver);
445 parsed.bigNumber === math.bignumber('1.5'); // true
446}
447
448/*
449Extend functionality with import
450 */
451
452declare module 'mathjs' {
453 interface MathJsStatic {
454 testFun(): number;
455 value: number;
456 }
457}
458
459{
460 const math = create(all, {});
461 const testFun = () => 5;
462
463 math.import(
464 {
465 testFun,
466 value: 10,
467 },
468 {}
469 );
470
471 math.testFun();
472
473 const a = math.value * 2;
474}
475
476/*
477Renamed functions from v5 => v6
478 */
479{
480 const math = create(all, {});
481 math.typeOf(1);
482 math.variance([1, 2, 3, 4]);
483 math.evaluate('1 + 2');
484
485 // chained operations
486 math.chain(3).typeOf().done();
487 math.chain([1, 2, 3]).variance().done();
488 math.chain('1 + 2').evaluate().done();
489}
490
491/*
492Factory Test
493 */
494{
495 // create a factory function
496 const name = 'negativeSquare';
497 const dependencies: MathJsFunctionName[] = ['multiply', 'unaryMinus'];
498 const createNegativeSquare = factory(name, dependencies, (injected) => {
499 const { multiply, unaryMinus } = injected;
500 return function negativeSquare(x: number): number {
501 return unaryMinus(multiply(x, x));
502 };
503 });
504
505 // create an instance of the function yourself:
506 const multiply = (a: number, b: number) => a * b;
507 const unaryMinus = (a: number) => -a;
508 const negativeSquare = createNegativeSquare({ multiply, unaryMinus });
509 negativeSquare(3);
510}
511
512/**
513 * Dependency map typing test from mathjs official document:
514 * https://mathjs.org/docs/custom_bundling.html#using-just-a-few-functions
515 */
516{
517 const config = {
518 // optionally, you can specify configuration
519 };
520
521 // Create just the functions we need
522 const { fraction, add, divide, format } = create(
523 {
524 fractionDependencies,
525 addDependencies,
526 divideDependencies,
527 formatDependencies,
528 },
529 config
530 );
531
532 // Use the created functions
533 const a = fraction(1, 3);
534 const b = fraction(3, 7);
535 const c = add(a, b);
536 const d = divide(a, b);
537 console.log('c =', format(c)); // outputs "c = 16/21"
538 console.log('d =', format(d)); // outputs "d = 7/9"
539}
540
541/**
542 * Custom parsing functions
543 * https://mathjs.org/docs/expressions/customization.html#customize-supported-characters
544 */
545{
546 const math = create(all, {});
547 const isAlphaOriginal = math.parse.isAlpha;
548 math.parse.isAlpha = (c, cPrev, cNext) => {
549 return isAlphaOriginal(c, cPrev, cNext) || c === "\u260E";
550 };
551
552 // now we can use the \u260E (phone) character in expressions
553 const result = math.evaluate("\u260Efoo", { "\u260Efoo": 42 }); // returns 42
554 console.log(result);
555}