在 NumPy 中返回下一个浮点值并将结果存储到新的位置
要在 Python NumPy 中按元素返回一个值之后朝另一个值方向的下一个浮点值,请使用 **numpy.nextafter()** 方法。第一个参数是要查找其下一个可表示值的数值。第二个参数是查找下一个可表示值的方向。我们将存储结果的新位置是一个新的数组。
此函数返回 x1 朝 x2 方向的下一个可表示值。如果 x1 和 x2 都是标量,则它也是标量。
out 是存储结果的位置。如果提供,则其形状必须与输入广播到的形状相同。如果不提供或为 None,则返回一个新分配的数组。元组(仅作为关键字参数可能)的长度必须等于输出的数量。
条件在输入上广播。在条件为 True 的位置,out 数组将设置为 ufunc 结果。在其他位置,out 数组将保留其原始值。请注意,如果通过默认的 out=None 创建未初始化的 out 数组,则其中条件为 False 的位置将保持未初始化。
步骤
首先,导入所需的库:
import numpy as np
使用 array() 方法创建两个零维 NumPy 数组:
arr1 = np.array(0.1) arr2 = np.array(-np.inf)
显示数组:
print("Array 1...
", arr1)
print("
Array 2...
", arr2)获取数组的类型:
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)获取数组的维度:
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)创建另一个具有相同形状的数组来存储结果:
arrRes = np.array(8.7)
要返回一个值之后朝另一个值方向的下一个浮点值,请使用 numpy.nextafter() 方法。我们将存储结果的新位置是 arrRes:
print("
The next floating-point value...
",np.nextafter(arr1, arr2, arrRes))检查存储结果的新数组的值:
print("
Result...
",arrRes)
示例
import numpy as np
# Creating two zero dimensional numpy array using the array() method
arr1 = np.array(0.1)
arr2 = np.array(-np.inf)
# Display the arrays
print("Array 1...
", arr1)
print("
Array 2...
", arr2)
# Get the type of the arrays
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)
# Get the dimensions of the Arrays
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)
# Create another array with the same shape to store the result
arrRes = np.array(8.7)
# To return the next floating-point value after a value towards another value, element-wise, use the numpy.nextafter() method in Python Numpy
# The 1st parameter is the value to find the next representable value of.
# The 2nd parameter is the direction where to look for the next representable value.
# The new location where we will store the result is arrRes
print("
The next floating-point value...
",np.nextafter(arr1, arr2, arrRes))
# Check the value of the new array where our result is stored
print("
Result...
",arrRes)输出
Array 1... 0.1 Array 2... -inf Our Array 1 type... float64 Our Array 2 type... float64 Our Array 1 Dimensions... 0 Our Array 2 Dimensions... 0 The next floating-point value... 0.09999999999999999 Result... 0.09999999999999999
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP