不同数值公差的不同 Equality[DenseVector] 类型

Different Equality[DenseVector] types for different numerical tolerances

我已经为 DenseVectors 编写了一个 scalactic 相等提供程序,它使用 breeze closeTo 方法来检查向量中的每个 double 是否足够接近。

 implicit val vectorEquality: Equality[DenseVector[Double]] = new Equality[DenseVector[Double]] {
    def areEqual(a: DenseVector[Double], b: Any): Boolean = {
      b match {
        case b: DenseVector[Double] => (a.valuesIterator zip b.valuesIterator).forall(p =>
          closeTo(p._1, p._2))
        case _ => false
      }
    }

当我在测试中使用这个相等性时,有什么方法可以控制 closeTo 的接近程度吗?有时我希望测试中的 "should be equal" 表示等于小数点后两位,而其他时候我想要更严格的要求。

是的,您可以控制接近度,因为 closeTo 在 Implicits 中定义了第三个参数,称为公差。

class RichDouble(x: Double) {
    def closeTo(y: Double, tol: Double=1E-5) = {
      (math.abs(x - y) / (math.abs(x) + math.abs(y) + 1e-10) < tol);
    }
    def isDangerous = x.isNaN || x.isInfinite
}

可以在 Chi Squared distribution

的测试中找到示例
def paramsClose(p: Double, b: Double) = breeze.numerics.closeTo(p, b, 5E-2)