比较 D 中的浮点数
Comparing floating point numbers in D
我目前正在实施四元数,我 运行 解决了以下问题
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 中的浮点数?
您可以使用标准库中的approxEqual函数
我目前正在实施四元数,我 运行 解决了以下问题
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 中的浮点数?
您可以使用标准库中的approxEqual函数