Ratio
Ratio
0
Howard Hinnant
Beman Dawes
Vicente J. Botet Escriba
Copyright © 2008 Howard Hinnant
Copyright © 2006, 2008 Beman Dawes
Copyright © 2009-2012 Vicente J. Botet Escriba
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
[Link]
Table of Contents
Overview .............................................................................................................................................................. 2
Motivation .................................................................................................................................................... 2
Description ................................................................................................................................................... 2
User's Guide ......................................................................................................................................................... 3
Getting Started .............................................................................................................................................. 3
Tutorial ........................................................................................................................................................ 5
Example ....................................................................................................................................................... 7
External Resources ....................................................................................................................................... 10
Reference ........................................................................................................................................................... 12
Header <boost/ratio/[Link]> ........................................................................................................... 12
C++0x Recommendation ............................................................................................................................... 13
Ratio I/O .................................................................................................................................................... 19
Rational Constant ......................................................................................................................................... 25
Appendices ......................................................................................................................................................... 34
Appendix A: History ..................................................................................................................................... 34
Appendix B: Rationale .................................................................................................................................. 35
Appendix C: Implementation Notes ................................................................................................................. 36
Appendix D: FAQ ......................................................................................................................................... 39
Appendix E: Acknowledgements ..................................................................................................................... 39
Appendix F: Tests ......................................................................................................................................... 39
Appendix G: Tickets ..................................................................................................................................... 41
Appendix H: Future Plans .............................................................................................................................. 42
Overview
How to Use This Documentation
This documentation makes use of the following naming and formatting conventions.
• Free functions are rendered in the code font followed by (), as in free_function().
• If a name refers to a class template, it is specified like this: class_template<>; that is, it is in code font and its name is followed
by <> to indicate that it is a class template.
• If a name refers to a function-like macro, it is specified like this: MACRO(); that is, it is uppercase in code font and its name is
followed by () to indicate that it is a function-like macro. Object-like macros appear without the trailing ().
• Names that refer to concepts in the generic programming sense are specified in CamelCase.
Note
In addition, notes such as this one specify non-essential information that provides additional background or rationale.
Finally, you can mentally add the following to any code fragments in this document:
Motivation
[Link] aims to implement the compile time ratio facility in C++0x, as proposed in N2661 - A Foundation to Sleep On. That
document provides background and motivation for key design decisions and is the source of a good deal of information in this doc-
umentation.
Description
The [Link] library provides:
• A class template, ratio, for specifying compile time rational constants such as 1/3 of a nanosecond or the number of inches per
meter. ratio represents a compile time ratio of compile time constants with support for compile time arithmetic with overflow
and division by zero protection.
• It provides a textual representation of boost::ratio<N, D> in the form of a std::basic_string which can be useful for
I/O.
• Some extension related to the Rational Constant concept enabling the use of ratio<> in the context of [Link] numeric
metafunctions.
User's Guide
Getting Started
Installing Ratio
Getting [Link]
[Link] is in the latest Boost release in the folder /boost/ratio. Documentation, tests and examples folder are at
boost/libs/ratio/.
You can also access the latest (unstable?) state from the Boost trunk directories boost/ratio and libs/ratio.
Just go to the wiki and follow the instructions there for anonymous SVN access.
The simple way is to decompress (or checkout from SVN) the files in your BOOST_ROOT directory.
Building [Link]
[Link] is a header only library, so no need to compile anything, you just need to include <boost/[Link]>.
Requirements
[Link] depends on some Boost libraries. For these specific parts you must use either Boost version 1.39.0 or later (even older
versions may work).
No link is needed.
Exception safety
All functions in the library are exception-neutral, providing the strong exception safety guarantee.
Thread safety
All functions in the library are thread-unsafe except when noted explicitly.
Tested compilers
[Link] should work with an C++03 conforming compiler. The current version has been tested on:
Windows with
• MSVC 10.0
MinGW with
• GCC 4.5.0
• GCC 4.5.2
• GCC 4.6.0
Ubuntu with * GCC 4.4.6 * GCC 4.4.6 -std=c++0x * GCC 4.5.4 * GCC 4.5.4 -std=c++0x * GCC 4.6.1 * GCC 4.6.1 -std=c++0x *
Intel 12.1.3 * Intel 12.1.3 -std=c++0x
OsX with
• GCC 4.1.2
• GCC 4.6.2
• GCC 4.7.0
• GCC 4.7.1
• clang 1.6
• clang 2.9
• clang 3.0
• clang 3.1
• clang 3.2
Note
Please let us know how this works on other platforms/compilers.
Note
Please send any questions, comments and bug reports to boost <at> lists <dot> boost <dot> org.
Tutorial
Ratio
ratio is a general purpose utility inspired by Walter Brown allowing one to easily and safely compute rational values at compile-
time. The ratio class catches all errors (such as divide by zero and overflow) at compile time. It is used in the duration and
time_point classes to efficiently create units of time. It can also be used in other "quantity" libraries or anywhere there is a rational
constant which is known at compile-time. The use of this utility can greatly reduce the chances of run-time overflow because the
ratio (and any ratios resulting from ratio arithmetic) are always reduced to the lowest terms.
ratio is a template taking two intmax_ts, with the second defaulted to 1. In addition to copy constructors and assignment, it only
has two public members, both of which are static const intmax_t. One is the numerator of the ratio and the other is the
denominator. The ratio is always normalized such that it is expressed in lowest terms, and the denominator is always positive.
When the numerator is 0, the denominator is always 1.
Example:
This facility also includes convenience typedefs for the SI prefixes atto through exa corresponding to their internationally recognized
definitions (in terms of ratio). This is a tremendous syntactic convenience. It will prevent errors in specifying constants as one no
longer has to double count the number of zeros when trying to write millions or billions.
Example:
Ratio I/O
For each ratio<N, D> there exists a ratio_string<ratio<N, D>, CharT> for which you can query two strings: symbol and
prefix. For those ratio's that correspond to an SI prefix prefix corresponds to the internationally recognized prefix, stored as a
basic_string<CharT>. For example ratio_string<mega, char>::prefix() returns string("mega"). For those ratios
that correspond to an SI prefix symbol corresponds to the internationally recognized symbol, stored as a basic_string<CharT>.
For example, ratio_string<mega, char>::symbol() returns string("M"). For all other ratios, both prefix() and sym-
bol() return a basic_string containing "[ratio::num/ratio::den]".
• char: UTF-8
• char16_t: UTF-16
• char32_t: UTF-32
When the character is char, UTF-8 will be used to encode the names. When the character is char16_t, UTF-16 will be used to encode
the names. When the character is char32_t, UTF-32 will be used to encode the names. When the character is wchar_t, the encoding
will be UTF-16 if wchar_t is 16 bits, and otherwise UTF-32.
Examples:
#include <boost/ratio/ratio_io.hpp>
#include <iostream>
int main()
{
using namespace std;
using namespace boost;
Example
SI units
This example illustrates the use of type-safe physics code interoperating with boost::chrono::duration types, taking advantage
of the [Link] infrastructure and design philosophy.
Let's start by defining a length class template that mimics boost::chrono::duration, which represents a time duration in
various units, but restricts the representation to double and uses [Link] for length unit conversions:
Note that since length's template parameter is actually a generic ratio type, so we can use boost::ratio allowing for more complex
length units:
Finally, we can write a proof-of-concept of an SI units library, hard-wired for meters and floating point seconds, though it will accept
other units:
template <>
class quantity<boost::ratio<1>, boost::ratio<0> >
{
double q_;
public:
quantity() : q_(1) {}
quantity(seconds d) : q_([Link]()) {} // note: only User1::seconds needed here
template <>
class quantity<boost::ratio<0>, boost::ratio<1> >
{
double q_;
public:
quantity() : q_(1) {}
quantity(meter d) : q_([Link]()) {} // note: only User1::meter needed here
template <>
class quantity<boost::ratio<0>, boost::ratio<0> >
{
double q_;
public:
quantity() : q_(1) {}
quantity(double d) : q_(d) {}
With all of the foregoing scaffolding, we can now write an exemplar of a type-safe physics function:
Distance
compute_distance(Speed v0, Time t, Acceleration a)
{
return v0 * t + Scalar(.5) * a * t * t; // if a units mistake is made here it won't compile
}
Finally, we can exercise what we've created, even using custom time durations (User1::seconds) as well as Boost time durations
(boost::chrono::hours). The input can be in arbitrary, though type-safe, units, the output is always in SI units. (A complete
Units library would support other units, of course.)
int main()
{
typedef boost::ratio<8, BOOST_INTMAX_C(0x7FFFFFFFD)> R1;
typedef boost::ratio<3, BOOST_INTMAX_C(0x7FFFFFFFD)> R2;
typedef User1::quantity<boost::ratio_subtract<boost::ratio<0>, boost::ratio<1> >::type,
boost::ratio_subtract<boost::ratio<1>, boost::ratio<0> >::type > RR;
typedef boost::ratio_subtract<R1, R2>::type RS;
std::cout << RS::num << '/' << RS::den << '\n';
RR r=d / t;
//[Link]([Link]() / [Link]());
User1::Speed rc= r;
User1::Speed s = d / t;
std::cout << "Speed = " << [Link]() << " meters/sec\n";
User1::Acceleration a = User1::Distance( User1::foot(32.2) ) / User1::Time() / User1::Time();
std::cout << "Acceleration = " << [Link]() << " meters/sec^2\n";
User1::Distance df = compute_distance(s, User1::Time( User1::seconds(0.5) ), a);
std::cout << "Distance = " << [Link]() << " meters\n";
std::cout << "There are "
<< User1::mile::ratio::den << '/' << User1::mile::ratio::num << " miles/meter";
User1::meter mt = 1;
User1::mile mi = mt;
std::cout << " which is approximately " << [Link]() << '\n';
std::cout << "There are "
<< User1::mile::ratio::num << '/' << User1::mile::ratio::den << " meters/mile";
mi = 1;
mt = mi;
std::cout << " which is approximately " << [Link]() << '\n';
User1::attosecond as(1);
User1::seconds sec = as;
std::cout << "1 attosecond is " << [Link]() << " seconds\n";
std::cout << "sec = as; // compiles\n";
sec = User1::seconds(1);
as = sec;
std::cout << "1 second is " << [Link]() << " attoseconds\n";
std::cout << "as = sec; // compiles\n";
std::cout << "\n";
return 0;
}
External Resources
C++ Standards Committee's cur- The most authoritative reference material for the library is the C++ Standards Committee's
rent Working Paper current Working Paper (WP). 20.6 Compile-time rational arithmetic "ratio"
10
N2661 - A Foundation to Sleep On From Howard E. Hinnant, Walter E. Brown, Jeff Garland and Marc Paterno. Is very inform-
ative and provides motivation for key design decisions
11
Reference
Header <boost/ratio/[Link]>
// Configuration macros
#define BOOST_RATIO_VERSION
#define BOOST_RATIO_EXTENSIONS
#define BOOST_RATIO_PROVIDES_DEPRECATED_FEATURES_SINCE_V2_0_0
#define BOOST_RATIO_DONT_PROVIDE_DEPRECATED_FEATURES_SINCE_V2_0_0
#define BOOST_RATIO_USES_STATIC_ASSERT
#define BOOST_RATIO_USES_MPL_ASSERT
#define BOOST_RATIO_USES_ARRAY_ASSERT
Extensions
When BOOST_RATIO_EXTENSIONS is defined, [Link] provides in addition some extension to the C++ standard, see below.
Deprecated
When BOOST_RATIO_PROVIDES_DEPRECATED_FEATURES_SINCE_V2_0_0 is defined the deprecated features stated as DEPREC-
ATED V2 are provided.
Version
BOOST_RATIO_VERSION stands for the [Link] version which can be 1 or 2. The default up to 1.55 is version 1. Since 1.56 it
will be 2.
Static Assert
When BOOST_NO_STATIC_ASSERT is defined, the user can select the way static assertions are reported. Define
When BOOST_RATIO_USES_MPL_ASSERT is not defined the following symbols are defined as shown:
12
Depending upon the static assertion system used, a hint as to the failing assertion will appear in some form in the compiler diagnostic
output.
C++0x Recommendation
Header <boost/[Link]>
This header includes all the ratio related header files
#include <boost/ratio/[Link]>
#include <boost/ratio/ratio_io.hpp>
#include <boost/ratio/rational_constant.hpp>
Header <boost/ratio/ratio_fwd.hpp>
This header provides forward declarations for the <boost/ratio/[Link]> file.
namespace boost {
// ratio arithmetic
template <class R1, class R2> struct ratio_add;
template <class R1, class R2> struct ratio_subtract;
template <class R1, class R2> struct ratio_multiply;
template <class R1, class R2> struct ratio_divide;
#ifdef BOOST_RATIO_EXTENSIONS
template <class R,int P> struct ratio_power;
template <class R> struct ratio_negate;
template <class R> struct ratio_sign;
template <class R> struct ratio_abs;
template <class R1, class R2> struct ratio_gcd;
template <class R1, class R2> struct ratio_lcm;
#endif
// ratio comparison
template <class R1, class R2> struct ratio_equal;
template <class R1, class R2> struct ratio_not_equal;
template <class R1, class R2> struct ratio_less;
template <class R1, class R2> struct ratio_less_equal;
template <class R1, class R2> struct ratio_greater;
template <class R1, class R2> struct ratio_greater_equal;
// convenience SI typedefs
typedef ratio<1LL, 1000000000000000000LL> atto;
typedef ratio<1LL, 1000000000000000LL> femto;
typedef ratio<1LL, 1000000000000LL> pico;
typedef ratio<1LL, 1000000000LL> nano;
typedef ratio<1LL, 1000000LL> micro;
typedef ratio<1LL, 1000LL> milli;
typedef ratio<1LL, 100LL> centi;
typedef ratio<1LL, 10LL> deci;
typedef ratio< 10LL, 1LL> deca;
typedef ratio< 100LL, 1LL> hecto;
typedef ratio< 1000LL, 1LL> kilo;
typedef ratio< 1000000LL, 1LL> mega;
typedef ratio< 1000000000LL, 1LL> giga;
typedef ratio< 1000000000000LL, 1LL> tera;
typedef ratio< 1000000000000000LL, 1LL> peta;
typedef ratio<1000000000000000000LL, 1LL> exa;
13
#ifdef BOOST_RATIO_EXTENSIONS
// convenience IEC typedefs
typedef ratio< 1024LL> kibi;
typedef ratio< 1024LL*1024LL> mebi;
typedef ratio< 1024LL*1024LL*1024LL> gibi;
typedef ratio< 1024LL*1024LL*1024LL*1024LL> tebi;
typedef ratio< 1024LL*1024LL*1024LL*1024LL*1024LL> pebi;
typedef ratio<1024LL*1024LL*1024LL*1024LL*1024LL*1024LL> exbi;
#endif
}
Header <boost/ratio/[Link]>
ratio is a facility which is useful in specifying compile-time rational constants. Compile-time rational arithmetic is supported with
protection against overflow and divide by zero. Such a facility is very handy to efficiently represent 1/3 of a nanosecond, or to specify
an inch in terms of meters (for example 254/10000 meters - which ratio will reduce to 127/5000 meters).
#ifdef BOOST_RATIO_EXTENSIONS
typedef mpl::rational_c_tag tag;
typedef boost::rational<boost::intmax_t> value_type;
typedef boost::intmax_t num_type;
typedef boost::intmax_t den_type;
ratio() = default;
A diagnostic will be emitted if ratio is instantiated with D == 0, or if the absolute value of N or D cannot be represented. Note:
These rules ensure that infinite ratios are avoided and that for any negative input, there exists a representable value of its absolute
value which is positive. In a two's complement representation, this excludes the most negative value.
The members num and den will be normalized values of the template arguments N and D computed as follows. Let gcd denote the
greatest common divisor of N's absolute value and of D's absolute value. Then:
The nested typedef type denotes the normalized form of this ratio type. It should be used when the normalized form of the template
arguments are required, since the arguments are not necessarily normalized.
14
Two ratio classes ratio<N1,D1> and ratio<N2,D2> have the same normalized form if ratio<N1,D1>::type is the same
type as ratio<N2,D2>::type
Default Constructor
ratio()=default;
Copy Constructor
Remarks: This constructor will not participate in overload resolution unless r has the same normalized form as *this.
Assignement
Returns: *this.
Remarks: This operator will not participate in overload resolution unless r has the same normalized form as *this.
In order to work with [Link] numeric metafunctions as a Rational Constant, the following has beed added:
Observers
Returns: value_type(num,den);
ratio Arithmetic
For each of the class templates in this section, each template parameter refers to a ratio. If the implementation is unable to form
the indicated ratio due to overflow, a diagnostic will be issued.
15
ratio_add<>
The nested typedef type is a synonym for ratio<R1::num * R2::den + R2::num * R1::den, R1::den * R2::den>::type.
ratio_subtract<>
The nested typedef type is a synonym for ratio<R1::num * R2::den - R2::num * R1::den, R1::den * R2::den>::type.
ratio_multiply<>
The nested typedef type is a synonym for ratio<R1::num * R2::num, R1::den * R2::den>::type.
ratio_divide<>
The nested typedef type is a synonym for ratio<R1::num * R2::den, R2::num * R1::den>::type.
ratio_power<>
ratio_negate<>
This extension of the C++ standard helps in the definition of some [Link] numeric metafunctions.
ratio_abs<>
16
This extension of the C++ standard helps in the definition of some [Link] numeric metafunctions.
ratio_sign<>
This extension of the C++ standard helps in the definition of some [Link] numeric metafunctions.
ratio_gcd<>
This extension of the C++ standard helps in the definition of some [Link] numeric metafunctions.
The nested typedef type is a synonym for ratio<gcd_c<intmax_t, R1::num, R2::num>::value, mpl::lcm_c<intmax_t,
R1::den, R2::den>::value>::type.
ratio_lcm<>
This extension of the C++ standard helps in the definition of some [Link] numeric metafunctions.
The nested typedef type is a synonym for ratio<lcm_c<intmax_t, R1::num, R2::num>::value, gcd_c<intmax_t,
R1::den, R2::den>::value>::type.
ratio Comparison
ratio_equal<>
If R1::num == R2::num && R1::den == R2::den, ratio_equal derives from true_type, else derives from false_type.
17
ratio_not_equal<>
ratio_less<>
If R1::num * R2::den < R2::num * R1::den, ratio_less derives from true_type, else derives from false_type.
ratio_less_equal<>
ratio_greater<>
ratio_greater_equal<>
SI typedefs
The International System of Units specifies twenty SI prefixes. [Link] defines all except yocto, zepto, zetta, and yotta
// convenience SI typedefs
typedef ratio<1LL, 1000000000000000000LL> atto;
typedef ratio<1LL, 1000000000000000LL> femto;
typedef ratio<1LL, 1000000000000LL> pico;
typedef ratio<1LL, 1000000000LL> nano;
typedef ratio<1LL, 1000000LL> micro;
typedef ratio<1LL, 1000LL> milli;
typedef ratio<1LL, 100LL> centi;
typedef ratio<1LL, 10LL> deci;
typedef ratio< 10LL, 1LL> deca;
typedef ratio< 100LL, 1LL> hecto;
typedef ratio< 1000LL, 1LL> kilo;
typedef ratio< 1000000LL, 1LL> mega;
typedef ratio< 1000000000LL, 1LL> giga;
typedef ratio< 1000000000000LL, 1LL> tera;
typedef ratio< 1000000000000000LL, 1LL> peta;
typedef ratio<1000000000000000000LL, 1LL> exa;
IEC typedefs
Included only if BOOST_RATIO_EXTENSIONS is defined.
The Specific units of IEC 60027-2 A.2 and ISO/IEC 80000 specifies height IEC prefixes. [Link] defines all except zebi and
yobi
18
Limitations
The following are limitations of [Link] relative to the specification in the C++0x draft standard:
• Four of the SI units typedefs -- yocto, zepto, zetta, and yotta -- are to be conditionally supported, if the range of intmax_t
allows, but are not supported by [Link].
• Ratio values should be of type static constexpr intmax_t (see Ratio values should be constexpr), but for compiler not supporting
constexpr today, [Link] uses static const intmax_t instead.
• Rational arithmetic should use template aliases (see Rational Arithmetic should use template aliases), but those are not available
in C++03, so inheritance is used instead.
Extensions
When BOOST_RATIO_EXTENSIONS is defined [Link] provides the following extensions:
• Extends the requirements of the C++0x draft standard by making the copy constructor and copy assignment operator have the
same normalized form (see copy constructor and assignment between ratios having the same normalized form).
• More C++ standard like metafunctions applied to ratio types, like __static_abs or __static_negate.
• An __Boost_Mpl rational constant concept and the associated __Boost_Mpl arithmetic and comparison specializations including
__numeric_cast, __plus, __equal_to between others.
Ratio I/O
Header <boost/ratio/ratio_io.hpp>
This header provides ratio_string<> which can generate a textual representation of a ratio<> in the form of a std::ba-
sic_string<>. These strings can be useful for I/O.
19
namespace boost {
template <class Ratio, class charT> struct ratio_string;
20
21
The class template ratio_string provides textual representations of the associated ratio appropriate for the character type charT.
The primary template provides generic strings. Specializations provide the same static member functions but these functions return
the English SI prefix and symbol names as specified by the General Conference on Weights and Measures.
Returns: prefix().
Returns: prefix().
Returns: symbol().
For each specialization the table gives the return value for prefix() and symbol().
22
23
24
Rational Constant
Rational Constant Concept
Description
A Rational Constant is a holder class for a compile-time value of a rational type. Every Rational Constant is also a nullary
Metafunction, returning itself. A rational constant object is implicitly convertible to the corresponding run-time value of the rational
type.
Expression requirements
25
Expression semantics
Expression Semantics
Models
• ratio<>
Header <boost/ratio/mpl/rational_constant.hpp>
This header includes all the rational constant related header files
#include <boost/ratio/mpl/rational_c_tag.hpp>
#include <boost/ratio/mpl/numeric_cast.hpp>
#include <boost/ratio/mpl/[Link]>
#include <boost/ratio/mpl/[Link]>
Header <boost/ratio/mpl/rational_c_tag.hpp>
namespace boost {
namespace mpl {
}
}
Header <boost/ratio/mpl/numeric_cast.hpp>
namespace boost {
namespace mpl {
}
}
26
mpl::numeric_cast<> Specialization
A Integral Constant is seen as a ratio with numerator the Integral Constant value and denominator 1.
Header <boost/ratio/mpl/[Link]>
This header includes all the rational constant arithmetic MPL specializations.
#include <boost/ratio/mpl/[Link]>
#include <boost/ratio/mpl/[Link]>
#include <boost/ratio/mpl/[Link]>
#include <boost/ratio/mpl/[Link]>
#include <boost/ratio/mpl/[Link]>
#include <boost/ratio/mpl/[Link]>
#include <boost/ratio/mpl/[Link]>
#include <boost/ratio/mpl/[Link]>
#include <boost/ratio/mpl/[Link]>
Header <boost/ratio/mpl/[Link]>
namespace boost {
namespace mpl {
template<>
struct plus_impl< rational_c_tag,rational_c_tag >;
}
}
mpl::plus_impl<> Specialization
The specialization relays on the ratio_add template class.
template<>
struct plus_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_add<R1, R2>
{
};
};
Header <boost/ratio/mpl/[Link]>
namespace boost {
namespace mpl {
template<>
struct minus_impl< rational_c_tag,rational_c_tag >;
}
}
27
mpl::minus_impl<> Specialization
The specialization relays on the ratio_subtract template class.
template<>
struct plus_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_subtract<R1, R2>
{
};
};
Header <boost/ratio/mpl/[Link]>
namespace boost {
namespace mpl {
template<>
struct times_impl< rational_c_tag,rational_c_tag >;
}
}
mpl::times_impl<> Specialization
The specialization relays on the ratio_multiply template class.
template<>
struct times_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_multiply<R1, R2>
{
};
};
Header <boost/ratio/mpl/[Link]>
namespace boost {
namespace mpl {
template<>
struct divides_impl< rational_c_tag,rational_c_tag >;
}
}
mpl::divides_impl<> Specialization
The specialization relays on the ratio_divide template class.
template<>
struct divides_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_divide<R1, R2>
{
};
};
28
Header <boost/ratio/mpl/[Link]>
namespace boost {
namespace mpl {
template<>
struct gcd_impl< rational_c_tag,rational_c_tag >;
}
}
mpl::gcd_impl<> Specialization
The specialization relays on the ratio_gcd template class.
template<>
struct gcd_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_gcd<R1, R2>
{
};
};
Header <boost/ratio/mpl/[Link]>
namespace boost {
namespace mpl {
template<>
struct lcm_impl< rational_c_tag,rational_c_tag >;
}
}
mpl::lcm_impl<> Specialization
The specialization relays on the ratio_lcm template class.
template<>
struct lcm_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_lcm<R1, R2>
{
};
};
Header <boost/ratio/mpl/[Link]>
namespace boost {
namespace mpl {
template<>
struct negate_impl< rational_c_tag >;
}
}
mpl::negate_impl<> Specialization
The specialization relays on the ratio_negate template class.
29
template<>
struct negate_impl< rational_c_tag >
{
template< typename R > struct apply
: ratio_negate<R>
{
};
};
Header <boost/ratio/mpl/[Link]>
namespace boost {
namespace mpl {
template<>
struct abs_impl< rational_c_tag >;
}
}
mpl::abs_impl<> Specialization
The specialization relays on the ratio_abs template class.
template<>
struct abs_impl< rational_c_tag >
{
template< typename R > struct apply
: ratio_abs<R>
{
};
};
Header <boost/ratio/mpl/[Link]>
namespace boost {
namespace mpl {
template<>
struct sign_impl< rational_c_tag >;
}
}
mpl::sign_impl<> Specialization
The specialization relays on the ratio_sign template class.
template<>
struct sign_impl< rational_c_tag >
{
template< typename R > struct apply
: ratio_sign<R>
{
};
};
Header <boost/ratio/mpl/[Link]>
This header includes all the rational constant comparison MPL specializations.
30
#include <boost/ratio/mpl/equal_to.hpp>
#include <boost/ratio/mpl/not_equal_to.hpp>
#include <boost/ratio/mpl/[Link]>
#include <boost/ratio/mpl/less_equal.hpp>
#include <boost/ratio/mpl/[Link]>
#include <boost/ratio/mpl/greater_equal.hpp>
Header <boost/ratio/mpl/equal_to.hpp>
namespace boost {
namespace mpl {
template<>
struct equal_to_impl< rational_c_tag,rational_c_tag >;
}
}
mpl::equal_to_impl<> Specialization
The specialization relays on the ratio_equal template class.
template<>
struct equal_to_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_equal<R1, R2>
{
};
};
Header <boost/ratio/mpl/not_equal_to.hpp>
namespace boost {
namespace mpl {
template<>
struct not_equal_to_impl< rational_c_tag,rational_c_tag >;
}
}
mpl::not_equal_to_impl<> Specialization
The specialization relays on the ratio_not_equal template class.
template<>
struct not_equal_to_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_not_equal<R1, R2>
{
};
};
31
Header <boost/ratio/mpl/[Link]>
namespace boost {
namespace mpl {
template<>
struct less_impl< rational_c_tag,rational_c_tag >;
}
}
mpl::less_impl<> Specialization
The specialization relays on the ratio_less template class.
template<>
struct less_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_less<R1, R2>
{
};
};
Header <boost/ratio/mpl/less_equal.hpp>
namespace boost {
namespace mpl {
template<>
struct less_equal_impl< rational_c_tag,rational_c_tag >;
}
}
mpl::less_equal_impl<> Specialization
The specialization relays on the ratio_less_equal template class.
template<>
struct less_equal_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_less_equal<R1, R2>
{
};
};
Header <boost/ratio/mpl/[Link]>
namespace boost {
namespace mpl {
template<>
struct greater_impl< rational_c_tag,rational_c_tag >;
}
}
mpl::greater_impl<> Specialization
The specialization relays on the ratio_greater template class.
32
template<>
struct greater_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_greater<R1, R2>
{
};
};
Header <boost/ratio/mpl/greater_equal.hpp>
namespace boost {
namespace mpl {
template<>
struct greater_equal_impl< rational_c_tag,rational_c_tag >;
}
}
mpl::greater_equal_impl<> Specialization
The specialization relays on the ratio_greater_equal template class.
template<>
struct greater_equal_impl< rational_c_tag,rational_c_tag >
{
template< typename R1, typename R2 > struct apply
: ratio_greater_equal<R1, R2>
{
};
};
33
Appendices
Appendix A: History
Version 2.1.0, Febreary 1, 2014 - 1.56
New Features:
• #7616 br_mul::nan - warning C4293: '<<' : shift count negative or too big, undefined behavior`.
• Replace the short_name and long_name functions by symbol and prefix functions respectively.
Deprecated:
The ratio_string<>::short_name and ratio_string<>::long_name are deprecated. Use ratio_string<>::symbol and ratio_string<>::prefix
respectively. These functions be removed in 1.55.
Fixes:
• #7478 Compiles fails with compilers supporting char16_t and char32_t fails if the library doesn't provides std::u16string and
std::u32string.
• #7075 Workaround for error: the type of partial specialization template parameter constant "n1" depends on another template
parameter.
• Added MPL Rational Constant and the associated numeric metafunction specializations.
34
• Documentation revision.
Fixes:
Test:
• A more complete test has been included adapted from the test of from libc++/ratio.
Appendix B: Rationale
Why ratio needs CopyConstruction and Assignment from ratios having the same normalized
form
Current N3000 doesn't allows to copy-construct or assign ratio instances of ratio classes having the same normalized form.
ratio<1,3> r1;
ratio<3,9> r2;
r1 = r2; // (1)
ratio<1,3> r1;
ratio_subtract<ratio<2,3>,ratio<1,3> > r2=r1; // (2)
The type of ratio_subtract<ratio<2,3>,ratio<1,3> > could be ratio<3,9> so the compilation could fail in (2). It could
also be ratio<1,3> and the compilation succeeds.
35
[Link] implements some simplifications in order to reduce the possibility of overflow. The general ideas are:
• Use the gcd of some of the possible products that can overflow, and simplify before doing the product.
• Use some equivalences relations that avoid addition or subtraction that can overflow or underflow.
ratio_add
In
(n1/d1)+(n2/d2)=(n1*d2+n2*d1)/(d1*d2)
( ((gcd(n1,n2)*(n1/gcd(n1,n2))) * (d2/gcd(d1,d2))) +
((gcd(n1,n2)*(n2/gcd(n1,n2))) * (d1/gcd(d1,d2)))
)
--------------------------------------------------
( (d1 * d2) / gcd(d1,d2) )
Factorizing gcd(n1,n2)
( gcd(n1,n2) *
( ((n1/gcd(n1,n2)) * (d2/gcd(d1,d2))) + ((n2/gcd(n1,n2)) * (d1/gcd(d1,d2))) )
)
-------------------------------------------------------------------------------
( (d1 * d2) / gcd(d1,d2) )
Regrouping
36
( gcd(n1,n2) *
( ((n1/gcd(n1,n2)) * (d2/gcd(d1,d2))) + ((n2/gcd(n1,n2)) * (d1/gcd(d1,d2))) )
)
-------------------------------------------------------------------------------
( (d1 / gcd(d1,d2)) * d2 )
Dividing by d2
This expression correspond to the multiply of two ratios that have less risk of overflow as the initial numerators and denominators
appear now in most of the cases divided by a gcd.
ratio_multiply
In
(n1/d1)*(n2/d2)=((n1*n2)/(d1*d2))
(((n1/gcc(n1,d2))*n2)
---------------------
(d1*(d2/gcc(n1,d2))))
Dividing by gcc(n2,d1)
((n1/gcc(n1,d2))*(n2/gcc(n2,d1)))
---------------------------------
((d1/gcc(n2,d1))*(d2/gcc(n1,d2)))
And now all the initial numerator and denominators have been reduced, avoiding the overflow.
ratio_less
In order to evaluate
(n1/d1)<(n2/d2)
37
If sign(n1) == sign(n2) the result depends on the following after making the numerators positive
• When the sign is equal the technique used is to work with integer division and modulo when the signs are equal.
Let call Qi the integer division of ni and di, and Mi the modulo of ni and di.
ni = Qi * di + Mi and Mi < di
Form
((n1*d2)<(d1*n2))
we get
Developing
Dividing by d1*d2
depends only on Q1 and Q2 as Qi are integers and (Mi/di) <1 because Mi<di.
38
but the difference between two numbers between 0 and 1 can not be greater than 1, so the result is false.
Appendix D: FAQ
Appendix E: Acknowledgements
The library code was derived from Howard Hinnant's time2_demo prototype. Many thanks to Howard for making his code available
under the Boost license. The original code was modified by Beman Dawes to conform to Boost conventions.
Much thanks to Andrei Alexandrescu, Walter Brown, Peter Dimov, Jeff Garland, Terry Golubiewski, Daniel Krugler, Anthony
Williams.
Howard Hinnant, who is the real author of the library, has provided valuable feedback and suggestions during the development of
the library. In particular, The ratio_io.hpp source has been adapted from the experimental header <ratio_io> from Howard Hinnant.
The acceptance review of [Link] took place between October 2nd and 11th 2010. Many thanks to Anthony Williams, the review
manager, and to all the reviewers: Bruno Santos, Joel Falcou, Robert Stewart, Roland Bock, Tom Tan and Paul A. Bristol.
Thanks to Andrew Chinoff and Paul A. Bristol for his help polishing the documentation.
Appendix F: Tests
In order to test you need to run
bjam libs/ratio/test
39
cd libs/chrono/test
bjam ratio
ratio
comparison
40
arithmetic
Appendix G: Tickets
Ticket Description Resolution State
41
42