Function diff #

创建一个新矩阵或数组,计算给定数组元素之间的差值。可选的 dim 参数可用于指定要计算差值的维度。如果未传递维度参数,则假定为维度 0。

维度在 javascript 中是零基的,在解析器中是单基的,可以是数字或 bignumber。数组必须是“矩形的”,例如 [1, 2]。如果输入的是矩阵,则会以矩阵形式返回,但除此之外,所有矩阵都会被转换为数组。

Syntax #

math.diff(arr)
math.diff(arr, dim)

Parameters #

Parameter Type Description
arr Array | Matrix 一个数组或矩阵
dim number | BigNumber 维度

Returns #

Type Description
Array | Matrix 给定维度中数组元素的差值

Throws #

Type | Description —- | ———–

Examples #

const arr = [1, 2, 4, 7, 0]
math.diff(arr) // returns [1, 2, 3, -7] (no dimension passed so 0 is assumed)
math.diff(math.matrix(arr)) // returns Matrix [1, 2, 3, -7]

const arr = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [9, 8, 7, 6, 4]]
math.diff(arr) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]]
math.diff(arr, 0) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]]
math.diff(arr, 1) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]]
math.diff(arr, math.bignumber(1)) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]]

math.diff(arr, 2) // throws RangeError as arr is 2 dimensional not 3
math.diff(arr, -1) // throws RangeError as negative dimensions are not allowed

// These will all produce the same result
math.diff([[1, 2], [3, 4]])
math.diff([math.matrix([1, 2]), math.matrix([3, 4])])
math.diff([[1, 2], math.matrix([3, 4])])
math.diff([math.matrix([1, 2]), [3, 4]])
// They do not produce the same result as  math.diff(math.matrix([[1, 2], [3, 4]])) as this returns a matrix

另请参阅 #

sum, subtract, partitionSelect

Fork me on GitHub