Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 15 additions & 15 deletions include/boost/multiprecision/detail/default_ops.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1299,28 +1299,28 @@ inline BOOST_MP_CXX14_CONSTEXPR void eval_fmod(T& result, const T& a, const T& b
eval_floor(n, result);
eval_multiply(n, b);
eval_subtract(result, a, n);
if (eval_get_sign(result) != 0)

int c = eval_get_sign(result);
if (c != 0)
{
//
// Sanity check, that due to rounding errors in division,
// we haven't accidently calculated the wrong value:
// See https://github.com/boostorg/multiprecision/issues/604 for an example.
//
if (eval_get_sign(result) == eval_get_sign(b))
{
if (result.compare(b) >= 0)
{
eval_subtract(result, b);
}
}
else
{
n = b;
// The check is by magnitude, so the comparison reverses when the remainder
// is negative: see https://github.com/boostorg/multiprecision/issues/764
//

n = b;
if (c != eval_get_sign(b))
n.negate();
if (result.compare(n) >= 0)
{
eval_subtract(result, n);
}
int cmp = result.compare(n);
if (c < 0)
cmp = -cmp;
if (cmp >= 0)
{
eval_subtract(result, n);
}
}
}
Expand Down
50 changes: 50 additions & 0 deletions test/git_issue_604.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,56 @@ void test()
T r = boost::multiprecision::fmod(val1, val2);
BOOST_CHECK_EQUAL(r, T(0));
}
// Non-zero remainders with a negative dividend, see issue 764: both conventions
// agree at zero, so the cases above cannot tell them apart.
{
const T val1{-8.5};
const T val2{2.5};
T r = boost::multiprecision::fmod(val1, val2);
BOOST_CHECK_EQUAL(r, T(-1));
}
{
const T val1{-8.5};
const T val2{-2.5};
T r = boost::multiprecision::fmod(val1, val2);
BOOST_CHECK_EQUAL(r, T(-1));
}
{
const T val1{8.5};
const T val2{2.5};
T r = boost::multiprecision::fmod(val1, val2);
BOOST_CHECK_EQUAL(r, T(1));
}
{
const T val1{8.5};
const T val2{-2.5};
T r = boost::multiprecision::fmod(val1, val2);
BOOST_CHECK_EQUAL(r, T(1));
}
{
const T val1{0.5};
const T val2{-1};
T r = boost::multiprecision::fmod(val1, val2);
BOOST_CHECK_EQUAL(r, T(0.5));
}
{
const T val1{-0.5};
const T val2{1};
T r = boost::multiprecision::fmod(val1, val2);
BOOST_CHECK_EQUAL(r, T(-0.5));
}
{
const T val1{-0.5};
const T val2{-1};
T r = boost::multiprecision::fmod(val1, val2);
BOOST_CHECK_EQUAL(r, T(-0.5));
}
{
const T val1{0.5};
const T val2{1};
T r = boost::multiprecision::fmod(val1, val2);
BOOST_CHECK_EQUAL(r, T(0.5));
}
}


Expand Down
Loading