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