计算Python中无符号整数数组的第n个离散差分
要计算第 n 个离散差分,请使用 numpy.diff() 方法。给定轴上第一个差分是通过 out[i] = a[i+1] – a[i] 给出的,通过递归使用 diff 计算高阶差分。第一个参数是输入数组。第二个参数是 n,即要差分的次数。如果为零,则输入按原样返回。第三个参数是进行差分的轴,默认是最后一个轴。
第四个参数是要附加到输入数组的值或要插入的值,沿着轴进行差分。标量值在轴方向上扩展为具有长度1的数组,并沿着所有其他轴的除轴外的维度和形状必须与 a 匹配。
步骤
首先,导入所需的库 –
import numpy as np
使用 array() 方法创建一个numpy array。我们添加了无符号类型的元素。对于无符号整数数组,结果也将是无符号的 –
arr = np.array([1,0], dtype=np.uint8)
显示数组 –
print("Our Array...\n",arr)
检查维度 –
print("\nDimensions of our Array...\n",arr.ndim)
获取数据类型 –
print("\nDatatype of our Array object...\n",arr.dtype)
要计算第 n 个离散差分,请使用 numpy.diff() 方法。给定轴上第一个差分是通过 out[i] = a[i+1] – a[i] 给出的,通过递归使用 diff 计算高阶差分 –
print("\nDiscrete difference..\n",np.diff(arr))
示例
import numpy as np
# Creating a numpy array using the array() method
# We have added elements of unsigned type
# For unsigned integer arrays, the results will also be unsigned.
arr = np.array([1,0], dtype=np.uint8)
# Display the array
print("Our Array...\n",arr)
# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)
# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)
# To calculate the n-th discrete difference, use the numpy.diff() method
# The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively.
print("\nDiscrete difference..\n",np.diff(arr))
输出
Our Array...
[1 0]
Dimensions of our Array...
1
Datatype of our Array object...
uint8
Discrete difference..
[255]