ceil()
函数将数组中的浮点数元素向上取整到大于或等于该数组元素的最小整数。
示例
import numpy as np
array1 = np.array([1.2, 2.7, 3.5, 4.8, 5.1])
# round up each element in array1 using ceil()
result = np.ceil(array1)
print(result)
# Output: [2. 3. 4. 5. 6.]
ceil() 语法
ceil()
的语法是
numpy.ceil(array, out = None)
ceil() 参数
ceil()
函数接受以下参数
array
- 输入数组out
(可选) - 输出数组,结果将存储在此处
ceil() 返回值
ceil()
函数返回一个包含向上取整值的新数组。
示例 1:将 ceil() 用于二维数组
import numpy as np
# create a 2D array
array1 = np.array([[1.2, 2.7, 3.5],
[4.8, 5.1, 6.3],
[7.2, 8.5, 9.9]])
# round up the elements in a 2D array with numpy.ceil()
result = np.ceil(array1)
print("Rounded-up values:")
print(result)
输出
Rounded-up values: [[ 2. 3. 4.] [ 5. 6. 7.] [ 8. 9. 10.]]
在这里,我们使用 ceil()
函数向上取整 array1 中的每个元素。
值 1.2 向上取整为 2,值 2.7 向上取整为 3,依此类推。
注意:ceil()
函数返回一个与输入数组数据类型相同的数组,并且结果值为表示向上取整值的浮点数。
示例 2:创建不同的输出数组来存储结果
import numpy as np
# create an array
array1 = np.array([1.2, 2.7, 3.5, 4.9])
# create an empty array with the same shape as array1
result = np.zeros_like(array1)
# store the result of ceil() in out_array
np.ceil(array1, out=result)
print(result)
输出
[2. 3. 4. 5.]
在这里,ceil()
函数与 out
参数一起使用,该参数设置为 result。这确保了应用 ceil()
函数的结果存储在 result 中。