Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing floating point numbers in D

I am currently implementing Quaternions and I run into the following problem

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

Where it prints 1 but the assert fails, which means the value is very close to 1 but not exactly.

In my vector code I always used the following apporach

/**
      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;
}

Where I basically do abs( a - b ) < tolerance.

I could generalize this to something like this

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

and then I could rewrite

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

But now I am wondering if there is already a standard way of comparing floating point numbers in D?

like image 680
Maik Klein Avatar asked Feb 24 '26 20:02

Maik Klein


1 Answers

You can use approxEqual function from standard library

like image 57
Kozzi11 Avatar answered Feb 27 '26 02:02

Kozzi11