返回Python中N维数组的梯度
梯度使用二阶精确中心差分法在内部点计算,并在边界使用一阶或二阶精确单侧(前向或后向)差分法。因此,返回的梯度与输入数组具有相同的形状。第一个参数f是一个包含标量函数样本的N维数组。第二个参数是可变参数,即f值之间的间距。所有维度的默认单位间距。
第三个参数是edge_order{1, 2},即使用N阶精确差分法在边界计算梯度。默认值:1。第四个参数是梯度,它仅沿给定的轴或轴计算。默认值(axis = None)是计算输入数组所有轴的梯度。axis可以为负数,在这种情况下,它从最后一个轴计数到第一个轴。该方法返回一个ndarray列表,对应于f关于每个维度的导数。每个导数都与f具有相同的形状。
步骤
首先,导入所需的库:
import numpy as np
使用array()方法创建一个numpy数组。我们添加了浮点类型的元素:
arr = np.array([20, 35, 57, 70, 85, 120], dtype = float)
显示数组:
print("Our Array...\n",arr)检查维度:
print("\nDimensions of our Array...\n",arr.ndim)
获取数据类型:
print("\nDatatype of our Array object...\n",arr.dtype)梯度使用二阶精确中心差分法在内部点计算,并在边界使用一阶或二阶精确单侧(前向或后向)差分法。因此,返回的梯度与输入数组具有相同的形状:
print("\nResult (gradient)...\n",np.gradient(arr))
示例
import numpy as np
# Creating a numpy array using the array() method
# We have added elements of float type
arr = np.array([20, 35, 57, 70, 85, 120], dtype = float)
# 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)
# The gradient is computed using second order accurate central differences in the interior points and either first or second order accurate one-sides (forward or backwards) differences at the boundaries. The returned gradient hence has the same shape as the input array.
print("\nResult (gradient)...\n",np.gradient(arr))输出
Our Array... [ 20. 35. 57. 70. 85. 120.] Dimensions of our Array... 1 Datatype of our Array object... float64 Result (gradient)... [15. 18.5 17.5 14. 25. 35. ]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP