数据类型 #

math.js 的函数支持多种数据类型,包括原生的 JavaScript 类型以及 math.js 实现的更高级的类型。这些数据类型可以在计算中混合使用,例如将数字 (Number) 与复数 (Complex) 或数组 (Array) 相加。

支持的数据类型有

可以使用函数 math.typeOf(x) 来获取变量的类型。

示例用法

// use numbers
math.subtract(7.1, 2.3)          // 4.8
math.round(math.pi, 3)           // 3.142
math.sqrt(4.41e2)                // 21

// use BigNumbers
math.add(math.bignumber(0.1), math.bignumber(0.2)) // BigNumber, 0.3

// use bigint
math.add(300000000000000000n, 1n) // 300000000000000001n

// use Fractions
math.add(math.fraction(1), math.fraction(3)) // Fraction, 0.(3)

// use strings containing numbers
math.add('2', '3')               // 5
math.concat('2', '3')            // '23'
math.max('3', '2', '7')          // 7
math.compareNatural('10', '2')   // 1

// use complex numbers
const a = math.complex(2, 3)     // 2 + 3i
a.re                             // 2
a.im                             // 3
const b = math.complex('4 - 2i') // 4 - 2i
math.add(a, b)                   // 6 + i
math.sqrt(-4)                    // 2i

// use arrays
const array = [1, 2, 3, 4, 5]
math.factorial(array)            // Array,  [1, 2, 6, 24, 120]
math.add(array, 3)               // Array,  [3, 5, 6, 7, 8]

// use matrices
const matrix = math.matrix([1, 4, 9, 16, 25]) // Matrix, [1, 4, 9, 16, 25]
math.sqrt(matrix)                             // Matrix, [1, 2, 3, 4, 5]

// use units
const a = math.unit(55, 'cm')    // 550 mm
const b = math.unit('0.1m')      // 100 mm
math.add(a, b)                   // 0.65 m

// check the type of a variable
math.typeOf(2)                   // 'number'
math.typeOf(math.unit('2 inch')) // 'Unit'
math.typeOf(math.sqrt(-4))       // 'Complex'
Fork me on GitHub