在 Python NumPy 中同时返回元素级商和余数
要同时返回元素级的商和余数,请在 Python NumPy 中使用 **numpy.fmod()** 方法。这里,第一个参数是被除数数组。第二个参数是除数数组。
这是 C 库函数 fmod 的 NumPy 实现,余数与被除数 x1 具有相同的符号。它等效于 Matlab(TM) rem 函数,不应与 Python 模数运算符 x1 % x2 混淆。
条件在输入上广播。在条件为 True 的位置,out 数组将设置为 ufunc 结果。在其他地方,out 数组将保留其原始值。请注意,如果通过默认的 out=None 创建了一个未初始化的 out 数组,则其中条件为 False 的位置将保持未初始化状态。
步骤
首先,导入所需的库 -
import numpy as np
创建一个数组。这是被除数数组 -
arr = np.array([5, 9, 14, 22, 76, 81, 91])
显示数组 -
print("Array...
", arr)获取数组的类型 -
print("
Our Array type...
", arr.dtype)
获取数组的维度 -
print("
Our Array Dimension...
",arr.ndim)获取数组的形状 -
print("
Our Array Shape...
",arr.shape)
除数数组 -
divisor = np.array([3, 7, 3, 3, 2, 7, 7])
要同时返回元素级的商和余数,请使用 numpy.fmod() 方法。这里,第一个参数是被除数数组。第二个参数是除数数组 -
print("
Result...
",np.divmod(arr, divisor))
示例
import numpy as np
# Create an array
# This is the dividend array
arr = np.array([5, 9, 14, 22, 76, 81, 91])
# Display the array
print("Array...
", arr)
# Get the type of the array
print("
Our Array type...
", arr.dtype)
# Get the dimensions of the Array
print("
Our Array Dimension...
",arr.ndim)
# Get the shape of the Array
print("
Our Array Shape...
",arr.shape)
# Divisor array
divisor = np.array([3, 7, 3, 3, 2, 7, 7])
# To return the element-wise quotient and remainder simultaneously, use the numpy.fmod() method in Python Numpy
# Here, the 1st parameter is the Dividend array
# The 2nd parameter is the Divisor array
print("
Result...
",np.divmod(arr, divisor))输出
Array... [ 5 9 14 22 76 81 91] Our Array type... int64 Our Array Dimension... 1 Our Array Shape... (7,) Result... (array([ 1, 1, 4, 7, 38, 11, 13]), array([2, 2, 2, 1, 0, 4, 0]))
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP