Skip to content

Commit 318a13c

Browse files
committed
Value: Fix negative values in modulo operator
1 parent 3ee3065 commit 318a13c

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/scratch/value.h

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -247,12 +247,16 @@ class LIBSCRATCHCPP_EXPORT Value : public ValueVariant
247247
/*! Replaces the value with modulo of the value and the given value. */
248248
inline void mod(const Value &v)
249249
{
250-
if ((v == 0) || (m_type == Type::Infinity || m_type == Type::NegativeInfinity))
250+
if ((v == 0) || (m_type == Type::Infinity || m_type == Type::NegativeInfinity)) {
251251
m_type = Type::NaN;
252-
else if (v.m_type == Type::Infinity || v.m_type == Type::NegativeInfinity) {
252+
return;
253+
} else if (v.m_type == Type::Infinity || v.m_type == Type::NegativeInfinity) {
253254
return;
254255
}
255-
*this = fmod(toDouble(), v.toDouble());
256+
if (*this < 0 || v < 0)
257+
*this = fmod(v.toDouble() + fmod(toDouble(), -v.toDouble()), v.toDouble());
258+
else
259+
*this = fmod(toDouble(), v.toDouble());
256260
}
257261

258262
inline const Value &operator=(float v)
@@ -511,7 +515,10 @@ class LIBSCRATCHCPP_EXPORT Value : public ValueVariant
511515
else if (v2.m_type == Type::Infinity || v2.m_type == Type::NegativeInfinity) {
512516
return v1.toDouble();
513517
}
514-
return fmod(v1.toDouble(), v2.toDouble());
518+
if (v1 < 0 || v2 < 0)
519+
return fmod(v2.toDouble() + fmod(v1.toDouble(), -v2.toDouble()), v2.toDouble());
520+
else
521+
return fmod(v1.toDouble(), v2.toDouble());
515522
}
516523
};
517524

0 commit comments

Comments
 (0)