在 NumPy 中返回一个值朝向另一个值之后下一个浮点值
要在 NumPy 中逐元素返回一个值朝向另一个值之后下一个浮点值,可以使用 **numpy.nextafter()** 方法。第一个参数是要查找其下一个可表示值的值。第二个参数是查找下一个可表示值的方向。
该函数返回 x1 在 x2 方向上的下一个可表示值。如果 x1 和 x2 都是标量,则这是一个标量。
out 是将结果存储到的位置。如果提供,则其形状必须与输入广播到的形状相同。如果不提供或为 None,则返回一个新分配的数组。元组(仅可能作为关键字参数)的长度必须等于输出的数量。
条件在输入上进行广播。在条件为 True 的位置,out 数组将设置为 ufunc 结果。在其他位置,out 数组将保留其原始值。请注意,如果通过默认的 out=None 创建了一个未初始化的 out 数组,则其中条件为 False 的位置将保持未初始化状态。
步骤
首先,导入所需的库:
import numpy as np
要在 NumPy 中逐元素返回一个值朝向另一个值之后下一个浮点值,可以使用 numpy.nextafter() 方法。
检查浮点数和无穷大:
print("Result? ", np.nextafter(0.1, np.inf))
print("
Result? ", np.nextafter(0.1, -np.inf))检查整数和无穷大:
print("
Result? ", np.nextafter(5, np.inf))
print("
Result? ", np.nextafter(10, -np.inf))检查 NaN 和无穷大:
print("
Result? ", np.nextafter(np.nan, np.inf))
print("
Result? ", np.nextafter(np.nan, -np.inf))检查 NaN 和无穷大:
print("
Result? ", np.nextafter(np.nan, np.inf))
print("
Result? ", np.nextafter(np.nan, -np.inf))检查对数和无穷大:
print("
Result? ", np.nextafter(np.log(1), np.inf))
print("
Result? ", np.nextafter(np.log(2), -np.inf))示例
import numpy as np
# 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.
# Check for float and inf
print("Result? ", np.nextafter(0.1, np.inf))
print("
Result? ", np.nextafter(0.1, -np.inf))
# Check for int and inf
print("
Result? ", np.nextafter(5, np.inf))
print("
Result? ", np.nextafter(10, -np.inf))
# Check for nan and inf
print("
Result? ", np.nextafter(np.nan, np.inf))
print("
Result? ", np.nextafter(np.nan, -np.inf))
# Check for nan and inf
print("
Result? ", np.nextafter(np.nan, np.inf))
print("
Result? ", np.nextafter(np.nan, -np.inf))
# Check for log and inf
print("
Result? ", np.nextafter(np.log(1), np.inf))
print("
Result? ", np.nextafter(np.log(2), -np.inf))输出
Result? 0.10000000000000002 Result? 0.09999999999999999 Result? 5.000000000000001 Result? 9.999999999999998 Result? nan Result? nan Result? nan Result? nan Result? 5e-324 Result? 0.6931471805599452
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP