浮点比较STL,BOOST [英] Floating point comparison in STL, BOOST

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

问题描述

在STL或Boost中有一组通用的简单比较函数吗?

我发现的一个总是需要模板参数,和/或实例化一个
结构模板。



我正在寻找类似以下语法的内容:

  if(is_equal(x,y))
{
...
}

可以这样实现:

  template< typename T> 
bool is_equal(const T& x,const T& y)
{
return(fabs(x-y)< Precision< T> :: eps);
}

编辑:我将运算符更改为相等。 (见下面的注释)

解决方案

我不知道有任何库可以这么做,也许是因为它像一个简单的单线或可能是因为它被遗忘...

一般情况下,你确定你想设置一个给定类型的epsilon给定的价值...整个应用程序?就我个人而言,我想根据自己所做的操作对其进行自定义(即使默认设置会很好)。

至于您的操作员,为什么不自己设计?

 模板< class T> 
bool rough_eq(T lhs,T rhs,T epsilon = Precision T :: epsilon)// operator ==
{
return fabs(lhs -rhs)小量;
}

模板< class T>
bool rough_lt(T lhs,T rhs,T epsilon = Precision< T>ε)//运算符<
{
return rhs - lhs> = epsilon;
// tricky> =因为如果差值等于epsilon
//那么它们就不是每个rough_eq方法都相等
}

template< class T>
bool rough_lte(T lhs,T rhs,T epsilon = Precision T ::ε)//运算符< =
{
return rhs -lhs> -epsilon;

$ / code>

不等式和大于方法可以由此得到平凡的结果。 >

附加参数意味着您可能希望为给定的一组计算指定另一个值...应用程序范围的设置过于严格。

Is there in the STL or in Boost a set of generic simple comparison functions?

The one I found are always requiring template parameters, and/or instantiation of a struct template.

I'm looking for something with a syntax like :

if ( is_equal(x,y) )
{
   ...
}

Which could be implemented as :

template <typename T>
bool is_equal(const T& x, const T& y)
{
    return ( fabs(x - y) < Precision<T>::eps );
}

EDIT: I changed the operator to equal. (see comments below)

解决方案

I don't know of any library that does it, perhaps because it is as simple as a one-liner or perhaps because it was forgotten...

As generality goes though, are you sure you'd like to set up the epsilon for one given type at a given value... throughout the application ? Personally I'd like to customize it depending on the operations I am doing (even though a default would be nice).

As for your operators, why not devising them yourself ?

template <class T>
bool rough_eq(T lhs, T rhs, T epsilon = Precision<T>::epsilon) // operator==
{ 
  return fabs(lhs - rhs) < epsilon;
}

template <class T>
bool rough_lt(T lhs, T rhs, T epsilon = Precision<T>::epsilon) // operator<
{
  return rhs - lhs >= epsilon;
       // tricky >= because if the difference is equal to epsilon
       // then they are not equal per the rough_eq method
}

template <class T>
bool rough_lte(T lhs, T rhs, T epsilon = Precision<T>::epsilon) // operator<=
{
  return rhs - lhs > -epsilon;
}

The inequality and greater than methods can be trivially derived from this.

The additional parameter means that you may wish to specify another value for a given set of computations... an application-wide setting is too strict.

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

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