UNPKG

2.5 kBJavaScriptView Raw
1/**
2 * Math.js can easily be extended with functions and variables using the
3 * `import` function. The function `import` accepts a module name or an object
4 * containing functions and variables.
5 */
6
7// load math.js (using node.js)
8const math = require('../index')
9
10/**
11 * Define new functions and variables
12 */
13math.import({
14 myConstant: 42,
15 hello: function (name) {
16 return 'hello, ' + name + '!'
17 }
18})
19
20// defined methods can be used in both JavaScript as well as the parser
21print(math.myConstant * 2) // 84
22print(math.hello('user')) // 'hello, user!'
23
24print(math.eval('myConstant + 10')) // 52
25print(math.eval('hello("user")')) // 'hello, user!'
26
27/**
28 * Import the math library numbers.js, https://github.com/sjkaliski/numbers.js
29 * The library must be installed first using npm:
30 * npm install numbers
31 */
32try {
33 // load the numbers.js library
34 const numbers = require('numbers')
35
36 // import the numbers.js library into math.js
37 math.import(numbers, { wrap: true, silent: true })
38
39 if (math.fibonacci) {
40 // calculate fibonacci
41 print(math.fibonacci(7)) // 13
42 print(math.eval('fibonacci(7)')) // 13
43 }
44} catch (err) {
45 console.log('Warning: To use numbers.js, the library must ' +
46 'be installed first via `npm install numbers`.')
47}
48
49/**
50 * Import the math library numeric.js, https://github.com/sloisel/numeric
51 * The library must be installed first using npm:
52 * npm install numeric
53 */
54try {
55 // load the numeric.js library
56 const numeric = require('numeric')
57
58 // import the numeric.js library into math.js
59 math.import(numeric, { wrap: true, silent: true })
60
61 if (math.eig) {
62 // calculate eigenvalues of a matrix
63 print(math.eval('eig([1, 2; 4, 3])').lambda.x) // [5, -1]
64
65 // solve AX = b
66 const A = math.eval('[1, 2, 3; 2, -1, 1; 3, 0, -1]')
67 const b = [9, 8, 3]
68 print(math.solve(A, b)) // [2, -1, 3]
69 }
70} catch (err) {
71 console.log('Warning: To use numeric.js, the library must ' +
72 'be installed first via `npm install numeric`.')
73}
74
75/**
76 * By default, the function import does not allow overriding existing functions.
77 * Existing functions can be overridden by specifying option `override: true`
78 */
79math.import({
80 pi: 3.14
81}, {
82 override: true
83})
84
85print(math.pi) // returns 3.14 instead of 3.141592653589793
86
87/**
88 * Helper function to output a value in the console. Value will be formatted.
89 * @param {*} value
90 */
91function print (value) {
92 const precision = 14
93 console.log(math.format(value, precision))
94}