...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
#include <boost/multiprecision/tommath.hpp>
namespace boost{ namespace multiprecision{ typedef rational_adpater<tommath_int> tommath_rational; typedef number<tommath_rational > tom_rational; }} // namespaces
The tommath_rational
back-end
is used via the typedef boost::multiprecision::tom_rational
.
It acts as a thin wrapper around boost::rational<tom_int>
to provide a rational number type that
is a drop-in replacement for the native C++ number types, but with unlimited
precision.
The advantage of using this type rather than boost::rational<tom_int>
directly, is that it is expression-template
enabled, greatly reducing the number of temporaries created in complex
expressions.
There are also non-member functions:
tom_int numerator(const tom_rational&); tom_int denominator(const tom_rational&);
which return the numerator and denominator of the number.
Things you should know when using this type:
tom_rational
s
have the value zero (this the inherited Boost.Rational behavior).
std::overflow_error
being thrown.
std::runtime_error
being thrown if the string can not be interpreted as a valid rational
number.
#include <boost/multiprecision/tommath.hpp> using namespace boost::multiprecision; tom_rational v = 1; // Do some arithmetic: for(unsigned i = 1; i <= 1000; ++i) v *= i; v /= 10; std::cout << v << std::endl; // prints 1000! / 10 std::cout << numerator(v) << std::endl; std::cout << denominator(v) << std::endl; tom_rational w(2, 3); // Component wise constructor std::cout << w << std::endl; // prints 2/3