...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/cpp_int.hpp>
namespace boost{ namespace multiprecision{ typedef rational_adapter<cpp_int_backend<> > cpp_rational_backend; typedef number<cpp_rational_backend> cpp_rational; }} // namespaces
The cpp_rational_backend
type is used via the typedef boost::multiprecision::cpp_rational
.
It provides a rational number type that is a drop-in replacement for the
native C++ number types, but with unlimited precision.
As well as the usual conversions from arithmetic and string types, instances
of cpp_rational
are copy
constructible and assignable from type cpp_int
.
There is also a two argument constructor that accepts a numerator and denominator:
both of type cpp_int
.
There are also non-member functions:
cpp_int numerator(const cpp_rational&); cpp_int denominator(const cpp_rational&);
which return the numerator and denominator of the number.
Things you should know when using this type:
cpp_rational
s
have the value zero.
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/cpp_int.hpp> using namespace boost::multiprecision; cpp_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; cpp_rational w(2, 3); // component wise constructor std::cout << w << std::endl; // prints 2/3