Skip to content

Commit 8f95555

Browse files
committed
more robust floating point comparison
1 parent 9bf58c5 commit 8f95555

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

plotjuggler_base/include/PlotJuggler/plotdatabase.h

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,20 @@ class PlotGroup
124124
template <typename TypeX, typename Value>
125125
class PlotDataBase
126126
{
127+
template <typename T>
128+
static bool is_equal(const T& a, const T& b) const
129+
{
130+
if constexpr (std::is_floating_point_v<T>)
131+
{
132+
const auto eps = std::numeric_limits<T>::epsilon();
133+
return std::abs(a - b) <= (eps * std::max({ T(1), std::abs(a), std::abs(b) })));
134+
}
135+
else
136+
{
137+
return a == b; // Assuming StringRef has an equality operator
138+
}
139+
}
140+
127141
public:
128142
struct Point
129143
{
@@ -429,7 +443,7 @@ class PlotDataBase
429443
{
430444
if constexpr (std::is_arithmetic_v<Value> || std::is_same_v<Value, StringRef>)
431445
{
432-
if (!(p.y == *_const_y_value))
446+
if (!is_equal(p.y, *_const_y_value))
433447
{
434448
// Transition to variable mode
435449
transitionToVariableMode();
@@ -613,7 +627,7 @@ class PlotDataBase
613627
// Check if still constant (only for types that support equality comparison)
614628
if constexpr (std::is_arithmetic_v<Value> || std::is_same_v<Value, StringRef>)
615629
{
616-
if (!(p.y == *_const_y_value))
630+
if (!is_equal(p.y, *_const_y_value))
617631
{
618632
// Transition to variable mode
619633
transitionToVariableMode();
@@ -667,7 +681,7 @@ class PlotDataBase
667681
{
668682
if constexpr (std::is_arithmetic_v<Value> || std::is_same_v<Value, StringRef>)
669683
{
670-
if (!(p.y == *_const_y_value))
684+
if (!is_equal(p.y, *_const_y_value))
671685
{
672686
// Transition to variable mode
673687
transitionToVariableMode();
@@ -696,8 +710,8 @@ class PlotDataBase
696710
{
697711
if constexpr (std::is_arithmetic_v<TypeX>)
698712
{
699-
if (!_range_x_dirty &&
700-
(_x_data.front() == _range_x.max || _x_data.front() == _range_x.min))
713+
if (!_range_x_dirty && (is_equal(_x_data.front(), _range_x.max) ||
714+
is_equal(_x_data.front(), _range_x.min)))
701715
{
702716
_range_x_dirty = true;
703717
}
@@ -706,7 +720,8 @@ class PlotDataBase
706720
if constexpr (std::is_arithmetic_v<Value>)
707721
{
708722
if (!_const_y_value.has_value() && !_range_y_dirty &&
709-
(_y_data.front() == _range_y.max || _y_data.front() == _range_y.min))
723+
(is_equal(_y_data.front(), _range_y.max) ||
724+
is_equal(_y_data.front(), _range_y.min)))
710725
{
711726
_range_y_dirty = true;
712727
}

0 commit comments

Comments
 (0)