Mse*_*ade 1 python floating-point compare set
所以我想创建一组浮点数,其中两个数字在给定一定容差时被认为是相等的.例如,如果我有一套
a = set([1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
如果我添加元素1.00001,容差为1e-4,则结果集应为
{1, 2, 3}
Run Code Online (Sandbox Code Playgroud)
并不是
{1, 1.00001, 2, 3}
Run Code Online (Sandbox Code Playgroud)
在我看来,您应该只能够检查该集中的每个项目,并且,如果该项目与您要添加的项目之间的绝对差小于阈值,请不要添加它。
这样的事情应该可以解决问题:
def AddToSetWithThreshold(pSet, pValue, pThreshold):
vList = [entry for entry in pSet if abs(pValue - entry) < pThreshold]
if len(vList) == 0:
pSet.add(pValue)
a = set([1, 2, 3]) ; print(a)
AddToSetWithThreshold(a, 1.00001, 1e-4) ; print(a)
AddToSetWithThreshold(a, 1.00001, 1e-6) ; print(a)
Run Code Online (Sandbox Code Playgroud)
因为第一个加法太接近1而第二个加法太近,这将导致以下输出:
set([1, 2, 3])
set([1, 2, 3])
set([1, 2, 3, 1.00001])
Run Code Online (Sandbox Code Playgroud)
我们可以使用圆函数来检查 tolerance of 1e-4
a = set([1,2,3])
def add(number):
if(round(number,4) not in a):
a.add(number)
add(1)
print(a)
add(1.0000)
print(a)
add(1.0001)
print(a)
add(1.1)
print(a)
Run Code Online (Sandbox Code Playgroud)