在D语言中比较浮点数

3

我目前正在实现四元数,但遇到了以下问题

unittest{
    auto q1 = Quaternion(Vec3f(1, 0, 0), Degrees(90));
    writeln("length ", q1.magnitude);
    assert(q1.magnitude is 1.0f);
}

当它打印1但断言失败时,这意味着该值非常接近1但不完全相等。

在我的向量代码中,我总是使用以下方法:

/**
      Compares two vectors with a tolerance value, if the type of the vector
      is a floating pointer number.
*/
bool equals(Vec, T = Vec.Type)(const Vec v1, const Vec v2, T tolerance = kindaSmallNumber)
if(isVector!Vec && isFloatingPoint!(Vec.Type)){
    import std.math: abs;
    import breeze.meta: zip;
    import std.algorithm.iteration: map;
    import std.algorithm.searching: all;
    return zip(v1.data[], v2.data[]).map!(t => abs(t[0] - t[1]) < kindaSmallNumber).all;
}

我基本上执行的是abs(a-b) < tolerance

我可以将其推广到类似于以下内容:

bool equalsf(float a, float b, float tolerance = 0.00001){
    import std.math: abs;
    return abs( a - b ) < tolerance;
}

然后我可以重写。
unittest{
    auto q1 = Quaternion(Vec3f(1, 0, 0), Degrees(90));
    assert(q1.magnitude.equalsf(1.0f));
}

但是我现在想知道,在 D 语言中是否已经有一种标准的比较浮点数的方法?

2个回答

4

0

看一下 gfm,gl3n, 或者 m3d,它们都提供了向量和四元数类型。


这个回答确切地回答了问题的哪一部分? - weltensturm
它回答了作者不应该重复造轮子的元问题。此外,在今年的DConf上,有关浮点数学特别是比较的讨论。长话短说,不要将浮点数进行相等比较。 - burner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接