Zaxter5
Zaxter5

Reputation: 87

How to perform Modulo of boost::cpp_dec_float_50 and boost::int1024_t Data Types?

I'm trying to perform a modulo operation on two numbers. One is a cpp_dec_float_50 type (decimal) number, and the other is a int1024_t type number - both supplied by the Boost Multiprecision C++ library.

I've tried using the % operator, and the Standard Library's fmod() function, but alas they aren't designed for such data types. I've scoured the Boost documentation however there is no trace of a modulous alternative that would work with its own floating point data types.

Please note that the int1024_t value is very large.

There must be SOME way to perform a modulo operation on such values, hopefully someone can shed some light on it for me.

Cheers.

Upvotes: 1

Views: 348

Answers (1)

Serg Kryvonos
Serg Kryvonos

Reputation: 4667

Consider using this formula:

(a mod b) = (a*x mod b*x)/x

  1. Convert float into boost rational
  2. Multiply both numbers by denominator
  3. Perform the modulo on integer type numbers
  4. Form rational with result of modulo as numerator and preserved previous denominator
  5. Convert rational back into floating-point type if you need it

Here is the sample code:

boost::multiprecision::cpp_rational rational_a = a;
auto denominator = boost::multiprecision::denominator(rational_a)

auto result = boost::multiprecision::numerator(rational_a) % (denominator * b);

auto modulo = boost::multiprecision::cpp_rational(result, denominator);

auto back = static_cast<boost::cpp_dec_float_50>(modulo);

Upvotes: 0

Related Questions