UNPKG

1.4 kBJavaScriptView Raw
1// basic usage
2
3// load math.js (using node.js)
4const math = require('../index')
5
6// functions and constants
7console.log('functions and constants')
8print(math.round(math.e, 3)) // 2.718
9print(math.atan2(3, -3) / math.pi) // 0.75
10print(math.log(10000, 10)) // 4
11print(math.sqrt(-4)) // 2i
12print(math.pow([[-1, 2], [3, 1]], 2)) // [[7, 0], [0, 7]]
13print(math.derivative('x^2 + x', 'x')) // 2 * x + 1
14console.log()
15
16// expressions
17console.log('expressions')
18print(math.eval('1.2 * (2 + 4.5)')) // 7.8
19print(math.eval('12.7 cm to inch')) // 5 inch
20print(math.eval('sin(45 deg) ^ 2')) // 0.5
21print(math.eval('9 / 3 + 2i')) // 3 + 2i
22print(math.eval('det([-1, 2; 3, 1])')) // -7
23console.log()
24
25// chained operations
26console.log('chained operations')
27const a = math.chain(3)
28 .add(4)
29 .multiply(2)
30 .done()
31print(a) // 14
32console.log()
33
34// mixed use of different data types in functions
35console.log('mixed use of data types')
36print(math.add(4, [5, 6])) // number + Array, [9, 10]
37print(math.multiply(math.unit('5 mm'), 3)) // Unit * number, 15 mm
38print(math.subtract([2, 3, 4], 5)) // Array - number, [-3, -2, -1]
39print(math.add(math.matrix([2, 3]), [4, 5])) // Matrix + Array, [6, 8]
40console.log()
41
42/**
43 * Helper function to output a value in the console. Value will be formatted.
44 * @param {*} value
45 */
46function print (value) {
47 const precision = 14
48 console.log(math.format(value, precision))
49}