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?
You can use approxEqual function from standard library
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With