How to check the rate of difference of values

时间:2016-05-17 11:17:08

标签: ruby

I want to check if a value is enough similar to another.

For that purpose I wrote this:

class Numeric
  def differ_within(other, num)
    between?(other * (1 - num), other * (1 + num))
  end
end

This code works fine, but I want to know if there is a existing method like this in core ruby or active_support or something else.

And I couldn't come up with good name of the method. Do you have any idea of a name that represent more properly the function of the method.

1 个答案:

答案 0 :(得分:0)

我会推荐名称within_error_tolerance?或类似名称。在通话中它看起来像这样:

x.within_error_tolerance?(y, 0.05)

“不同”这个词在我看来是多余的。另外,我很惊讶你使用的是小数而不是绝对数量(即5%而不是120)(不是说使用分数是错的,这是有道理的,但我不清楚),所以方法名称传达它是一个分数是有帮助的。错误容差通常表示为百分比,因此在名称中使用“容错”对我来说很有意义。

另一个问题是,x是预期数量还是观察到的数量?假设:

class Numeric
  def within_error_tolerance?(other, tolerance)
    between?(other * (1 - tolerance), other * (1 + tolerance))
  end
end

然后切换参数和消息接收器将产生不同的结果:

2.3.0 :071 > 100.within_error_tolerance?(150, 0.4)
 => true
2.3.0 :072 > 150.within_error_tolerance?(100, 0.4)
 => false

......所以人们需要小心如何调用它。