Python - AI 助手

Python cmath.isclose() 函数



Python 的 cmath.isclose() 函数用于检查两个浮点数是否在指定的容差范围内彼此接近。如果给定值接近,则此函数返回 True,否则返回 False。

从数学角度来看,当两个数字彼此接近时,这些值表示为:

|a - b| ≤ max(rel_tol × max(|a|, |b|), abs_tol)
  • 如果两个数字之间的绝对差小于或等于相对容差,则此函数返回“True”;否则返回“False”。
  • 如果 a 和 b 的值都是 NaN,则结果始终为 False。

语法

以下是 Python cmath.isclose() 函数的基本语法:

cmath.isclose(a, b, *, rel_tol=1e-9, abs_tol=0.0)

参数

  • a − 表示第一个数字的数值。
  • b − 表示第二个数字的数值。
  • rel_tol − 相对容差,以浮点数表示。相对容差的默认值为 1e-9。
  • abs_tol − 绝对容差,以浮点数表示。绝对容差的默认值为 0.0。

返回值

此方法返回布尔值,即 True 或 False。

示例 1

在下面的示例中,我们将使用 cmath.isclose() 函数检查 0.2 和 0.3 的和是否等于 0.5。如果值相等,则将返回 True。

import cmath
x = cmath.isclose(0.2+0.3,  0.5)
print(x)

输出

得到的输出如下:

True

示例 2

在这里,我们使用cmath.isclose()函数和绝对容差“0.02”,检查数字“2000”和“2002”是否相等,相对容差为“0.002”。

import cmath
res = cmath.isclose(2000, 2002, rel_tol=0.002, abs_tol=0.02)
print(res)

输出

以下是上述代码的输出:

True

示例 3

在下面的示例中,我们使用cmath.isclose()函数比较大数,即“1e10”和“1e10+1”,相对容差为“0.001”。

import cmath 
x = cmath.isclose(1e10, 1e10+1, rel_tol=0.001)
print(x)

输出

结果如下:

True
python_modules.htm
广告
© . All rights reserved.