问题描述
在我的C ++项目中,由于数字错误,我经常遇到不准确的结果。以某种方式重新定义标准比较运算符( ==
, ,> =
,
,>
),以便他们不比较恰好但在可接受的错误内(例如 1e-12
)?
(如果是,这是一个好主意这样做?)
(当然可以编写比较功能,但人们直观地使用运算符。)
解决方案要重载操作符,一些参数必须是用户定义的类型。内置的是固定的,不变的。
但是即使这样做也不会是一件好事。自己一个忙,并提供您的自定义比较运算符作为一组函数,选择一个隐含其使用策略的名称。您不能指望代码阅读器在没有适当指示的情况下知道相等的手段是严格的,或者使用DBL_EPSILON或2 * DBL_EPSILON或某些任意的线性或标度公差。
In my C++ project I frequently encounter inexact results due to numerical errors. Is it somehow possible to somehow redefine the standard comparison operators (==
, <=
, >=
, <
, >
) so that they do not compare exactly but within an acceptable error (e.g. 1e-12
) ?
(If yes, is it a good idea to do this?)
(Of course one could write comparison functions but people intuitively use the operators.)
解决方案 To overload operators some argument must be user-defined type. The built-in ones are fixed and unchangeable.
But even if you could it would hardly be a good thing. Do yourself a favor, and provide your custom compare "operators" as a set of functions, choosing a name that implies the strategy they use. You can't expect a code reader to know without proper indication that equal means strict or with DBL_EPSILON or 2*DBL_EPSILON or some arbitrary linear or scaled tolerance.
这篇关于超载比较为双,允许数字错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!