浮点数集 [英] Set of floating point numbers

查看:77
本文介绍了浮点数集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想创建一组浮点数,其中在给定一定公差的情况下,两个数被视为相等.例如,如果我有一套

So I want to create a set of floating point numbers where two numbers are considered equal given a certain tolerance. For example, if I have a set

a =  set([1, 2, 3])

如果我添加公差为1e-4的元素1.00001,则结果集应为

if I add the element 1.00001 with a tolerance of 1e-4, the resulting set should be

{1, 2, 3}

而不是

{1, 1.00001, 2, 3}

推荐答案

我们可以使用舍入函数来检查 1e-4的容差

We can use a round function to check 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)

这篇关于浮点数集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆