Skip to content

Implement floor() and ceil() for rational types. #214

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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
20 changes: 20 additions & 0 deletions include/boost/multiprecision/rational_adaptor.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,26 @@ inline number<IntBackend, ET> denominator(const number<rational_adaptor<IntBacke
{
return val.backend().data().denominator();
}
template <class IntBackend, expression_template_option ET>
inline number<IntBackend, ET> floor(const number<rational_adaptor<IntBackend>, ET>& val)
{
// Here we use the assumption that denominator is always positive
// and numerator has the sign
if (val >= 0)
return numerator(val) / denominator(val);
else
return (numerator(val) + 1) / denominator(val) - 1;
}
template <class IntBackend, expression_template_option ET>
inline number<IntBackend, ET> ceil(const number<rational_adaptor<IntBackend>, ET>& val)
{
// Here we use the assumption that denominator is always positive
// and numerator has the sign
if (val >= 0)
return (numerator(val) - 1) / denominator(val) + 1;
else
return numerator(val) / denominator(val);
}

#ifdef BOOST_NO_SFINAE_EXPR

Expand Down
11 changes: 11 additions & 0 deletions test/test_arithmetic.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,17 @@ void test_rational(const boost::mpl::false_&)
#endif
b = Real("2/3");
BOOST_CHECK_EQUAL(a, b);

const static int floor_ceil_data[][4] = {{-11, 10, -2, -1}, {-10, 10, -1, -1}, {-9, 10, -1, 0},
{-1, 10, -1, 0}, {0, 10, 0, 0}, {1, 10, 0, 1},
{9, 10, 0, 1}, {10, 10, 1, 1}, {11, 10, 1, 2}};
for (unsigned int i = 0; i < sizeof(floor_ceil_data) / sizeof(floor_ceil_data[0]); i++) {
Real c(floor_ceil_data[i][0]);
c /= floor_ceil_data[i][1];
BOOST_CHECK_EQUAL(floor(c), floor_ceil_data[i][2]);
BOOST_CHECK_EQUAL(ceil(c), floor_ceil_data[i][3]);
}

//
// Check IO code:
//
Expand Down