isclose() 函数是Python中用于比较浮点数是否接近的函数。它用于在考虑浮点数精度的情况下,判断两个浮点数是否非常接近或相等。
isclose() 函数的语法如下:
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
其中,参数 ab 是要比较的两个浮点数。
rel_tol(相对容差)和 abs_tol(绝对容差)是可选参数,用于设置比较的容差范围。默认情况下,相对容差是 1e-09,绝对容差是 0.0
isclose() 函数会返回一个布尔值,表示两个浮点数是否接近。如果两个浮点数的差的绝对值小于等于给定的容差范围,则返回 True,否则返回 False
以下是 isclose() 函数的示例用法:
import math
x = 0.1 + 0.1 + 0.1
y = 0.3
if math.isclose(x, y):
    print("x and y are close")
else:
print("x and y are not close")
在上述示例中,由于浮点数的精度限制,xy 的实际值可能并不完全相等,但由于它们非常接近,因此 isclose() 函数将返回 True,并输出 "x and y are close"。
float()函数
通过使用 isclose() 函数,可以在进行浮点数比较时,考虑到浮点数的精度问题,避免由于精度误差带来的意外结果。