[/
Copyright 2011, 2013 John Maddock.
Copyright 2013 - 2019 Paul A. Bristow.
Copyright 2013 Christopher Kormanyos.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[library Boost.Multiprecision
[quickbook 1.7]
[copyright 2002-2020 John Maddock and Christopher Kormanyos]
[purpose Multiprecision Number library]
[license
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
[@http://www.boost.org/LICENSE_1_0.txt])
]
[authors [Maddock, John], [Kormanyos, Christopher]]
[/last-revision $Date: 2011-07-08 18:51:46 +0100 (Fri, 08 Jul 2011) $]
]
[import html4_symbols.qbk] [/Ideally this should be the same as Boost.Math I:\boost\libs\math\doc]
[import ../example/gmp_snips.cpp]
[import ../example/mpfr_snips.cpp]
[import ../example/mpfi_snips.cpp]
[import ../example/float128_snips.cpp]
[import ../example/cpp_dec_float_snips.cpp]
[import ../example/cpp_bin_float_snips.cpp]
[/import ../example/big_seventh.cpp]
[import ../example/cpp_int_import_export.cpp]
[import ../example/cpp_bin_float_import_export.cpp]
[import ../example/tommath_snips.cpp]
[import ../example/cpp_int_snips.cpp]
[import ../example/random_snips.cpp]
[import ../example/safe_prime.cpp]
[import ../example/mixed_integer_arithmetic.cpp]
[import ../example/logged_adaptor.cpp]
[import ../example/numeric_limits_snips.cpp]
[import ../example/hashing_examples.cpp]
[import ../example/cpp_complex_examples.cpp]
[import ../example/mpc_examples.cpp]
[import ../example/complex128_examples.cpp]
[import ../example/eigen_example.cpp]
[import ../example/mpfr_precision.cpp]
[import ../example/constexpr_float_arithmetic_examples.cpp]
[import ../test/constexpr_test_cpp_int_5.cpp]
[import ../test/constexpr_test_cpp_int_7.cpp]
[/External links as templates (see also some defs below)]
[template mpfr[] [@http://www.mpfr.org MPFR]]
[template mpc[] [@http://www.multiprecision.org MPC]]
[template mpfi[] [@http://perso.ens-lyon.fr/nathalie.revol/software.html MPFI]]
[template gmp[] [@http://gmplib.org GMP]]
[template mpf_class[] [@http://gmplib.org/manual/C_002b_002b-Interface-Floats.html#C_002b_002b-Interface-Floats mpf_class]]
[template mpfr_class[] [@http://math.berkeley.edu/~wilken/code/gmpfrxx/ mpfr_class]]
[template mpreal[] [@http://www.holoborodko.com/pavel/mpfr/ mpreal]]
[template mpir[] [@http://mpir.org/ MPIR]]
[template tommath[] [@http://libtom.net libtommath]]
[template quadmath[] [@http://gcc.gnu.org/onlinedocs/libquadmath/ libquadmath]]
[template super[x]''''''[x]'''''']
[template sub[x]''''''[x]'''''']
[/insert Equation as a PNG or SVG image, previous generated with an external tool like Latex.]
[/Used thus [equation ellint6] - without the file type suffix which will chosen automatically.]
[template equation[name] '''
''']
[/insert Indented one-line expression italic and serif font probably using Unicode symbols for Greek and symbols.]
[/Example: [expression [sub 1]F[sub 0](a, z) = (1-z)[super -a]]]
[template expression[equation]
[:
[role serif_italic [equation]]
]
[/ Hint you may need to enclose equation in brackets if it contains comma(s) to avoid "error invalid number of arguments"]
]
[def __tick [role aligncenter [role green \u2714]]] [/ u2714 is a HEAVY CHECK MARK tick (2713 check mark), green]
[def __cross [role aligncenter [role red \u2718]]] [/ u2718 is a heavy cross, red]
[def __star [role aligncenter [role red \u2736]]] [/ 6-point star red ]
[/Boost.Multiprecision internals links]
[def __cpp_int [link boost_multiprecision.tut.ints.cpp_int cpp_int]]
[def __gmp_int [link boost_multiprecision.tut.ints.gmp_int gmp_int]]
[def __tom_int [link boost_multiprecision.tut.ints.tom_int tom_int]]
[def __gmp_float [link boost_multiprecision.tut.floats.gmp_float gmp_float]]
[def __mpf_float [link boost_multiprecision.tut.floats.gmp_float gmp_float]]
[def __mpfr_float_backend [link boost_multiprecision.tut.floats.mpfr_float mpfr_float]]
[def __cpp_bin_float [link boost_multiprecision.tut.floats.cpp_bin_float cpp_bin_float]]
[def __cpp_dec_float [link boost_multiprecision.tut.floats.cpp_dec_float cpp_dec_float]]
[def __gmp_rational [link boost_multiprecision.tut.rational.gmp_rational gmp_rational]]
[def __cpp_rational [link boost_multiprecision.tut.rational.cpp_rational cpp_rational]]
[def __tommath_rational [link boost_multiprecision.tut.rational.tommath_rational tommath_rational]]
[def __number [link boost_multiprecision.ref.number number]]
[def __float128__ [link boost_multiprecision.tut.floats.float128 float128]]
[def __cpp_complex [link boost_multiprecision.tut.complex.cpp_complex cpp_complex]]
[def __mpc_complex [link boost_multiprecision.tut.complex.mpc_complex mpc_complex]]
[def __debug_adaptor [link boost_multiprecision.tut.misc.debug_adaptor debug_adaptor]]
[def __logged_adaptor [link boost_multiprecision.tut.misc.logged_adaptor logged_adaptor]]
[def __rational_adaptor [link boost_multiprecision.tut.rational.rational_adaptor rational_adaptor]]
[def __cpp_complex [link boost_multiprecision.tut.complex.cpp_complex cpp_complex]]
[def __mpc_complex [link boost_multiprecision.tut.complex.mpc_complex mpc_complex]]
[def __complex128 [link boost_multiprecision.tut.complex.complex128 complex128]]
[def __complex_adaptor [link boost_multiprecision.tut.complex.complex_adaptor complex_adaptor]]
[def __random [link boost_multiprecision.tut.random random number generation]]
[def __literals [link boost_multiprecision.tut.lits literals]]
[/External references links as macro definitions.]
[def __expression_template [@https://en.wikipedia.org/wiki/Expression_templates expression template]]
[def __expression_templates [@https://en.wikipedia.org/wiki/Expression_templates expression templates]] [/plural version]
[def __UDT [@http://eel.is/c++draft/definitions#defns.prog.def.type program-defined type]]
[def __fundamental_type [@https://en.cppreference.com/w/cpp/language/types fundamental (built-in) type]]
[def __fundamental_types [@https://en.cppreference.com/w/cpp/language/types fundamental (built-in) types]]
[def __fundamental [@https://en.cppreference.com/w/cpp/language/types fundamental (built-in)]]
[def __math_constants [@https://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/constants.html Boost.Math constants]]
[def __boost_macros [@https://www.boost.org/doc/libs/release/libs/config/doc/html/boost_config/boost_macro_reference.html Boost macros]]
[def __boost_config [@https://www.boost.org/doc/libs/release/libs/config/doc/html/index.html Boost.Config]]
[def __is_constant_evaluated [@https://en.cppreference.com/w/cpp/types/is_constant_evaluated `std::is_constant_evaluated`]]
[def __compiler_support [@https://en.cppreference.com/w/cpp/compiler_support compiler support]]
[def __ULP [@http://en.wikipedia.org/wiki/Unit_in_the_last_place Unit in the last place (ULP)]]
[def __Mathematica [@http://www.wolfram.com/products/mathematica/index.html Wolfram Mathematica]]
[def __WolframAlpha [@http://www.wolframalpha.com/ Wolfram Alpha]]
[def __Boost_Serialization [@https://www.boost.org/doc/libs/release/libs/serialization/doc/index.html Boost.Serialization]]
[def __Boost_Math [@https://www.boost.org/doc/libs/release/libs/math/doc/index.html Boost.Math]]
[def __Boost_Multiprecision [@https://www.boost.org/doc/libs/release/libs/multiprecision/doc/index.html Boost.Multiprecision]]
[section:intro Introduction]
The Multiprecision Library provides [link boost_multiprecision.tut.ints integer],
[link boost_multiprecision.tut.rational rational],
[link boost_multiprecision.tut.floats floating-point],
and [link boost_multiprecision.tut.complex complex] types in C++ that have more
range and precision than C++'s ordinary __fundamental types.
The big number types in Multiprecision can be used with a wide
selection of basic mathematical operations, elementary transcendental
functions as well as the functions in Boost.Math.
The Multiprecision types can also interoperate with any
__fundamental_type in C++ using clearly defined conversion rules.
This allows Boost.Multiprecision to be used for all
kinds of mathematical calculations involving integer,
rational and floating-point types requiring extended
range and precision.
Multiprecision consists of a generic interface to the
mathematics of large numbers as well as a selection of
big number back-ends, with support for integer, rational,
floating-point, and complex types. Boost.Multiprecision provides a selection
of back-ends provided off-the-rack in including
interfaces to GMP, MPFR, MPIR, MPC, TomMath as well as
its own collection of Boost-licensed, header-only back-ends for
integers, rationals and floats. In addition, user-defined back-ends
can be created and used with the interface of Multiprecision,
provided the class implementation adheres to the necessary
[link boost_multiprecision.ref.backendconc concepts].
Depending upon the number type, precision may be arbitrarily large
(limited only by available memory), fixed at compile time
(for example, 50 or 100 decimal digits), or a variable controlled at run-time
by member functions. The types are __expression_templates - enabled for
better performance than naive user-defined types.
The Multiprecision library comes in two distinct parts:
* An expression-template-enabled front-end `number`
that handles all the operator overloading, expression evaluation optimization, and code reduction.
* A selection of back-ends that implement the actual arithmetic operations, and need conform only to the
reduced interface requirements of the front-end.
Separation of front-end and back-end allows use of highly refined, but restricted license libraries
where possible, but provides Boost license alternatives for users who must have a portable
unconstrained license.
Which is to say some back-ends rely on 3rd party libraries,
but a header-only Boost license version is always available (if somewhat slower).
[h5:getting_started Getting started with Boost.Multiprecision]
Should you just wish to 'cut to the chase' just to get bigger integers and/or bigger and more precise reals as simply and portably as possible,
close to 'drop-in' replacements for the __fundamental_type analogs,
then use a fully Boost-licensed number type, and skip to one of more of :
* __cpp_int for multiprecision integers,
* __cpp_rational for rational types,
* __cpp_bin_float and __cpp_dec_float for multiprecision floating-point types,
* __cpp_complex for complex types.
The library is very often used via one of the predefined convenience `typedef`s
like `boost::multiprecision::int128_t` or `boost::multiprecision::cpp_bin_float_quad`.
For example, if you want a signed, 128-bit fixed size integer:
#include // Integer types.
boost::multiprecision::int128_t my_128_bit_int;
Alternatively, and more adventurously, if you wanted an
[@http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic arbitrary precision]
integer type using [gmp] as the underlying implementation then you could use:
#include // Defines the wrappers around the GMP library's types
boost::multiprecision::mpz_int myint; // Arbitrary precision integer type.
Or for a simple, portable 128-bit floating-point close to a drop-in for a __fundamental_type like `double`, usually 64-bit
#include
boost::multiprecision::cpp_bin_float_quad my_quad_real;
Alternatively, you can compose your own 'custom' multiprecision type, by combining `number` with one of the
predefined back-end types. For example, suppose you wanted a 300 decimal digit floating-point type
based on the [mpfr] library. In this case, there's no predefined `typedef` with that level of precision,
so instead we compose our own:
#include // Defines the Backend type that wraps MPFR.
namespace mp = boost::multiprecision; // Reduce the typing a bit later...
typedef mp::number > my_float;
my_float a, b, c; // These variables have 300 decimal digits precision.
We can repeat the above example, but with the expression templates disabled (for faster compile times, but slower runtimes)
by passing a second template argument to `number`:
#include // Defines the Backend type that wraps MPFR.
namespace mp = boost::multiprecision; // Reduce the typing a bit later...
typedef mp::number, et_off> my_float;
my_float a, b, c; // These variables have 300 decimal digits precision
We can also mix arithmetic operations between different types, provided there is an unambiguous implicit conversion from one
type to the other:
#include
namespace mp = boost::multiprecision; // Reduce the typing a bit later...
mp::int128_t a(3), b(4);
mp::int512_t c(50), d;
d = c * a; // OK, result of mixed arithmetic is an int512_t
Conversions are also allowed:
d = a; // OK, widening conversion.
d = a * b; // OK, can convert from an expression template too.
However conversions that are inherently lossy are either declared explicit or else forbidden altogether:
d = 3.14; // Error implicit conversion from double not allowed.
d = static_cast(3.14); // OK explicit construction is allowed
Mixed arithmetic will fail if the conversion is either ambiguous or explicit:
number, et_off> a(2);
number, et_on> b(3);
b = a * b; // Error, implicit conversion could go either way.
b = a * 3.14; // Error, no operator overload if the conversion would be explicit.
[h4 Move Semantics]
On compilers that support rvalue-references, class `number` is move-enabled if the underlying backend is.
In addition the non-expression template operator overloads (see below) are move aware and have overloads
that look something like:
template
number operator + (number&& a, const number& b)
{
return std::move(a += b);
}
These operator overloads ensure that many expressions can be evaluated without actually generating any temporaries.
However, there are still many simple expressions such as
a = b * c;
which don't noticeably benefit from move support. Therefore, optimal performance comes from having both
move-support, and expression templates enabled.
Note that while "moved-from" objects are left in a sane state, they have an unspecified value, and the only permitted
operations on them are destruction or the assignment of a new value. Any other operation should be considered
a programming error and all of our backends will trigger an assertion if any other operation is attempted. This behavior
allows for optimal performance on move-construction (i.e. no allocation required, we just take ownership of the existing
object's internal state), while maintaining usability in the standard library containers.
[h4:expression_templates Expression Templates]
Class `number` is expression-template-enabled: that means that rather than having a multiplication
operator that looks like this:
template
number operator * (const number& a, const number& b)
{
number result(a);
result *= b;
return result;
}
Instead the operator looks more like this:
template
``['unmentionable-type]`` operator * (const number& a, const number& b);
Where the '['unmentionable]' return type is an implementation detail that, rather than containing the result
of the multiplication, contains instructions on how to compute the result. In effect it's just a pair
of references to the arguments of the function, plus some compile-time information that stores what the operation
is.
The great advantage of this method is the ['elimination of temporaries]: for example, the "naive" implementation
of `operator*` above, requires one temporary for computing the result, and at least another one to return it. It's true
that sometimes this overhead can be reduced by using move-semantics, but it can't be eliminated completely. For example,
lets suppose we're evaluating a polynomial via Horner's method, something like this:
T a[7] = { /* some values */ };
//....
y = (((((a[6] * x + a[5]) * x + a[4]) * x + a[3]) * x + a[2]) * x + a[1]) * x + a[0];
If type `T` is a `number`, then this expression is evaluated ['without creating a single temporary value]. In contrast,
if we were using the [mpfr_class] C++ wrapper for [mpfr] - then this expression would result in no less than 11
temporaries (this is true even though [mpfr_class] does use expression templates to reduce the number of temporaries somewhat). Had
we used an even simpler wrapper around [mpfr] like [mpreal] things would have been even worse and no less that 24 temporaries
are created for this simple expression (note - we actually measure the number of memory allocations performed rather than
the number of temporaries directly, note also that the [mpf_class] wrapper that will be supplied with GMP-5.1 reduces the number of
temporaries to pretty much zero). Note that if we compile with expression templates disabled and rvalue-reference support
on, then actually still have no wasted memory allocations as even though temporaries are created, their contents are moved
rather than copied.
[footnote The actual number generated will depend on the compiler, how well it optimizes the code, and whether it supports
rvalue references. The number of 11 temporaries was generated with Visual C++ 2010.]
[important
Expression templates can radically reorder the operations in an expression, for example:
a = (b * c) * a;
Will get transformed into:
a *= c;
a *= b;
If this is likely to be an issue for a particular application, then they should be disabled.
]
This library also extends expression template support to standard library functions like `abs` or `sin` with `number`
arguments. This means that an expression such as:
y = abs(x);
can be evaluated without a single temporary being calculated. Even expressions like:
y = sin(x);
get this treatment, so that variable 'y' is used as "working storage" within the implementation of `sin`,
thus reducing the number of temporaries used by one. Of course, should you write:
x = sin(x);
Then we clearly can't use `x` as working storage during the calculation, so then a temporary variable
is created in this case.
Given the comments above, you might be forgiven for thinking that expression-templates are some kind of universal-panacea:
sadly though, all tricks like this have their downsides. For one thing, expression template libraries
like this one, tend to be slower to compile than their simpler cousins, they're also harder to debug
(should you actually want to step through our code!), and rely on compiler optimizations being turned
on to give really good performance. Also, since the return type from expressions involving `number`s
is an "unmentionable implementation detail", you have to be careful to cast the result of an expression
to the actual number type when passing an expression to a template function. For example, given:
template
void my_proc(const T&);
Then calling:
my_proc(a+b);
Will very likely result in obscure error messages inside the body of `my_proc` - since we've passed it
an expression template type, and not a number type. Instead we probably need:
my_proc(my_number_type(a+b));
Having said that, these situations don't occur that often - or indeed not at all for non-template functions.
In addition, all the functions in the Boost.Math library will automatically convert expression-template arguments
to the underlying number type without you having to do anything, so:
mpfr_float_100 a(20), delta(0.125);
boost::math::gamma_p(a, a + delta);
Will work just fine, with the `a + delta` expression template argument getting converted to an `mpfr_float_100`
internally by the Boost.Math library.
[caution In C++11 you should never store an expression template using:
`auto my_expression = a + b - c;`
unless you're absolutely sure that the lifetimes of `a`, `b` and `c` will outlive that of `my_expression`.
In fact, it is particularly easy to create dangling references by mixing expression templates with the `auto`
keyword, for example:
`auto val = cpp_dec_float_50("23.1") * 100;`
In this situation, the integer literal is stored directly in the expression template - so its use is OK here -
but the `cpp_dec_float_50` temporary is stored by reference and then destructed when the statement completes,
leaving a dangling reference.
[*['If in doubt, do not ever mix expression templates with the `auto` keyword.]]
]
And finally... the performance improvements from an expression template library like this are often not as
dramatic as the reduction in number of temporaries would suggest. For example, if we compare this library with
[mpfr_class] and [mpreal], with all three using the underlying [mpfr] library at 50 decimal digits precision then
we see the following typical results for polynomial execution:
[table Evaluation of Order 6 Polynomial.
[[Library] [Relative Time] [Relative number of memory allocations]]
[[number] [1.0 (0.00957s)] [1.0 (2996 total)]]
[[[mpfr_class]] [1.1 (0.0102s)] [4.3 (12976 total)]]
[[[mpreal]] [1.6 (0.0151s)] [9.3 (27947 total)]]
]
As you can see, the execution time increases a lot more slowly than the number of memory allocations. There are
a number of reasons for this:
* The cost of extended-precision multiplication and division is so great, that the times taken for these tend to
swamp everything else.
* The cost of an in-place multiplication (using `operator*=`) tends to be more than an out-of-place
`operator*` (typically `operator *=` has to create a temporary workspace to carry out the multiplication, where
as `operator*` can use the target variable as workspace). Since the expression templates carry out their
magic by converting out-of-place operators to in-place ones, we necessarily take this hit. Even so the
transformation is more efficient than creating the extra temporary variable, just not by as much as
one would hope.
Finally, note that `number` takes a second template argument, which, when set to `et_off` disables all
the expression template machinery. The result is much faster to compile, but slower at runtime.
We'll conclude this section by providing some more performance comparisons between these three libraries,
again, all are using [mpfr] to carry out the underlying arithmetic, and all are operating at the same precision
(50 decimal digits):
[table Evaluation of Boost.Math's Bessel function test data
[[Library] [Relative Time] [Relative Number of Memory Allocations]]
[[mpfr_float_50] [1.0 (5.78s)] [1.0 (1611963)]]
[[number, et_off>[br](but with rvalue reference support)]
[1.1 (6.29s)] [2.64 (4260868)]]
[[[mpfr_class]] [1.1 (6.28s)] [2.45 (3948316)]]
[[[mpreal]] [1.65 (9.54s)] [8.21 (13226029)]]
]
[table Evaluation of Boost.Math's Non-Central T distribution test data
[[Library][Relative Time][Relative Number of Memory Allocations]]
[[number] [1.0 (263s)][1.0 (127710873)]]
[[number, et_off>[br](but with rvalue reference support)]
[1.0 (260s)][1.2 (156797871)]]
[[[mpfr_class]] [1.1 (287s)][2.1 (268336640)]]
[[[mpreal]] [1.5 (389s)][3.6 (466960653)]]
]
The above results were generated on Win32 compiling with Visual C++ 2010, all optimizations on (/Ox),
with MPFR 3.0 and MPIR 2.3.0.
[endsect] [/section:intro Introduction]
[section:tut Tutorial]
In order to use this library you need to make two choices:
* What kind of number do I want ([link boost_multiprecision.tut.ints integer],
[link boost_multiprecision.tut.floats floating-point], [link boost_multiprecision.tut.rational rational], or [link boost_multiprecision.tut.complex complex]).
* Which back-end do I want to perform the actual arithmetic (Boost-supplied, GMP, MPFR, MPC, Tommath etc)?
[section:ints Integer Types]
The following back-ends provide integer arithmetic:
[table
[[Backend Type][Header][Radix][Dependencies][Pros][Cons]]
[[`cpp_int`][boost/multiprecision/cpp_int.hpp][2][None]
[Very versatile, Boost licensed, all C++ integer type which support both [@http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic arbitrary precision] and fixed precision integer types.][Slower than [gmp], though typically not as slow as [tommath]]]
[[`gmp_int`][boost/multiprecision/gmp.hpp][2][[gmp]][Very fast and efficient back-end.][Dependency on GNU licensed [gmp] library.]]
[[`tom_int`][boost/multiprecision/tommath.hpp][2][[tommath]][Public domain back-end with no licence restrictions.][Slower than [gmp].]]
]
[section:cpp_int cpp_int]
`#include `
namespace boost{ namespace multiprecision{
typedef unspecified-type limb_type;
enum cpp_integer_type { signed_magnitude, unsigned_magnitude };
enum cpp_int_check_type { checked, unchecked };
template >
class cpp_int_backend;
//
// Expression templates default to et_off if there is no allocator:
//
template
struct expression_template_default >
{ static const expression_template_option value = et_off; };
typedef number > cpp_int; // arbitrary precision integer
typedef rational_adaptor > cpp_rational_backend;
typedef number cpp_rational; // arbitrary precision rational number
// Fixed precision unsigned types:
typedef number > uint128_t;
typedef number > uint256_t;
typedef number > uint512_t;
typedef number > uint1024_t;
// Fixed precision signed types:
typedef number > int128_t;
typedef number > int256_t;
typedef number > int512_t;
typedef number > int1024_t;
// Over again, but with checking enabled this time:
typedef number > checked_cpp_int;
typedef rational_adaptor > checked_cpp_rational_backend;
typedef number checked_cpp_rational;
// Checked fixed precision unsigned types:
typedef number > checked_uint128_t;
typedef number > checked_uint256_t;
typedef number > checked_uint512_t;
typedef number > checked_uint1024_t;
// Fixed precision signed types:
typedef number > checked_int128_t;
typedef number > checked_int256_t;
typedef number > checked_int512_t;
typedef number > checked_int1024_t;
}} // namespaces
The `cpp_int_backend` type is normally used via one of the convenience typedefs given above.
This back-end is the "Swiss Army Knife" of integer types as it can represent both fixed and
[@http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic arbitrary precision]
integer types, and both signed and unsigned types. There are five template arguments:
[variablelist
[[MinBits][Determines the number of Bits to store directly within the object before resorting to dynamic memory
allocation. When zero, this field is determined automatically based on how many bits can be stored
in union with the dynamic storage header: setting a larger value may improve performance as larger integer
values will be stored internally before memory allocation is required.]]
[[MaxBits][Determines the maximum number of bits to be stored in the type: resulting in a fixed precision type.
When this value is the same as MinBits, then the Allocator parameter is ignored, as no dynamic
memory allocation will ever be performed: in this situation the Allocator parameter should be set to
type `void`. Note that this parameter should not be used simply to prevent large memory
allocations, not only is that role better performed by the allocator, but fixed precision
integers have a tendency to allocate all of MaxBits of storage more often than one would expect.]]
[[SignType][Determines whether the resulting type is signed or not. Note that for
[@http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic arbitrary precision] types
this parameter must be `signed_magnitude`. For fixed precision
types then this type may be either `signed_magnitude` or `unsigned_magnitude`.]]
[[Checked][This parameter has two values: `checked` or `unchecked`. See below.]]
[[Allocator][The allocator to use for dynamic memory allocation, or type `void` if MaxBits == MinBits.]]
]
When the template parameter Checked is set to `checked` then the result is a ['checked-integer], checked
and unchecked integers have the following properties:
[table
[[Condition][Checked-Integer][Unchecked-Integer]]
[[Numeric overflow in fixed precision arithmetic][Throws a `std::overflow_error`.][Performs arithmetic modulo 2[super MaxBits]]]
[[Constructing an integer from a value that can not be represented in the target type][Throws a `std::range_error`.]
[Converts the value modulo 2[super MaxBits], signed to unsigned conversions extract the last MaxBits bits of the
2's complement representation of the input value.]]
[[Unsigned subtraction yielding a negative value.][Throws a `std::range_error`.][Yields the value that would
result from treating the unsigned type as a 2's complement signed type.]]
[[Attempting a bitwise operation on a negative value.][Throws a `std::range_error`][Yields the value, but not the bit pattern,
that would result from performing the operation on a 2's complement integer type.]]
]
Things you should know when using this type:
* Default constructed `cpp_int_backend`s have the value zero.
* Division by zero results in a `std::overflow_error` being thrown.
* Construction from a string that contains invalid non-numeric characters results in a `std::runtime_error` being thrown.
* Since the precision of `cpp_int_backend` is necessarily limited when the allocator parameter is void,
care should be taken to avoid numeric overflow when using this type
unless you actually want modulo-arithmetic behavior.
* The type uses a sign-magnitude representation internally, so type `int128_t` has 128-bits of precision plus an extra sign bit.
In this respect the behaviour of these types differs from __fundamental 2's complement types. In might be tempting to use a
127-bit type instead, and indeed this does work, but behaviour is still slightly different from a 2's complement __fundamental type
as the minimum and maximum values are identical (apart from the sign), where as they differ by one for a true 2's complement type.
That said it should be noted that there's no requirement for fundamental_types to be 2's complement either - it's simply that this
is the most common format by far.
* Attempting to print negative values as either an Octal or Hexadecimal string results in a `std::runtime_error` being thrown,
this is a direct consequence of the sign-magnitude representation.
* The fixed precision types `[checked_][u]intXXX_t` have expression template support turned off - it seems to make little
difference to the performance of these types either way - so we may as well have the faster compile times by turning
the feature off.
* Unsigned types support subtraction - the result is "as if" a 2's complement operation had been performed as long as they are not
['checked-integers] (see above).
In other words they behave pretty much as a __fundamental integer type would in this situation. So for example if we were using
`uint128_t` then `uint128_t(1)-4` would result in the value `0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD`
of type `uint128_t`. However, had this operation been performed on `checked_uint128_t` then a `std::range_error` would have
been thrown.
* Unary negation of unsigned types results in a compiler error (static assertion).
* This backend supports rvalue-references and is move-aware, making instantiations of `number` on this backend move aware.
* When used at fixed precision, the size of this type is always one machine word (plus any compiler-applied alignment padding)
larger than you would expect for an N-bit integer:
the extra word stores both the sign, and how many machine words in the integer are actually in use.
The latter is an optimisation for larger fixed precision integers, so that a 1024-bit integer has almost the same performance
characteristics as a 128-bit integer, rather than being 4 times slower for addition and 16 times slower for multiplication
(assuming the values involved would always fit in 128 bits).
Typically this means you can use
an integer type wide enough for the "worst case scenario" with only minor performance degradation even if most of the time
the arithmetic could in fact be done with a narrower type.
Also note that unsigned fixed precision types small enough to fit inside the largest native integer become a simple wrapper around that type,
this includes the "checked" variants. Small signed types will always have an extra sign word and so be larger than their native equivalent.
* When used at fixed precision and MaxBits is smaller than the number of bits in the largest native integer type, then
internally `cpp_int_backend` switches to a "trivial" implementation where it is just a thin wrapper around a single
integer. Note that it will still be slightly slower than a bare native integer, as it emulates a
signed-magnitude representation rather than simply using the platforms native sign representation: this ensures
there is no step change in behavior as a cpp_int grows in size.
* Fixed precision `cpp_int`'s have some support for `constexpr` values and user-defined literals, see
[link boost_multiprecision.tut.lits here] for the full description. For example `0xfffff_cppi1024`
specifies a 1024-bit integer with the value 0xffff. This can be used to generate compile-time constants that are
too large to fit into any __fundamental number type.
* The __cpp_int types support constexpr arithmetic, provided it is a fixed-precision type with no allocator. It may also
be a checked integer: in which case a compiler error will be generated on overflow or undefined behaviour. In addition
the free functions `abs`, `swap`, `multiply`, `add`, `subtract`, `divide_qr`, `integer_modulus`, `powm`, `lsb`, `msb`,
`bit_test`, `bit_set`, `bit_unset`, `bit_flip`, `sqrt`, `gcd`, `lcm` are all supported. Use of __cpp_int in this way
requires either a C++2a compiler (one which supports `std::is_constant_evaluated()`), or GCC-6 or later in C++14 mode.
Compilers other than GCC and without `std::is_constant_evaluated()` will support a very limited set of operations:
expect to hit roadblocks rather easily.
* You can import/export the raw bits of a __cpp_int to and from external storage via the `import_bits` and `export_bits`
functions. More information is in the [link boost_multiprecision.tut.import_export section on import/export].
[h5:cpp_int_eg Example:]
[cpp_int_eg]
[endsect] [/section:cpp_int cpp_int]
[section:gmp_int gmp_int]
`#include `
namespace boost{ namespace multiprecision{
class gmp_int;
typedef number mpz_int;
}} // namespaces
The `gmp_int` back-end is used via the typedef `boost::multiprecision::mpz_int`. It acts as a thin wrapper around the [gmp] `mpz_t`
to provide an integer type that is a drop-in replacement for the native C++ integer types, but with unlimited precision.
As well as the usual conversions from arithmetic and string types, type `mpz_int` is copy constructible and assignable from:
* The [gmp] native types: `mpf_t`, `mpz_t`, `mpq_t`.
* Instances of `number` that are wrappers around those types: `number >`, `number`.
It's also possible to access the underlying `mpz_t` via the `data()` member function of `gmp_int`.
Things you should know when using this type:
* No changes are made to the GMP library's global settings - so you can safely mix this type with
existing code that uses [gmp].
* Default constructed `gmp_int`s have the value zero (this is GMP's default behavior).
* Formatted IO for this type does not support octal or hexadecimal notation for negative values,
as a result performing formatted output on this type when the argument is negative and either of the flags
`std::ios_base::oct` or `std::ios_base::hex` are set, will result in a `std::runtime_error` will be thrown.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be interpreted
as a valid integer.
* Division by zero results in a `std::overflow_error` being thrown.
* Although this type is a wrapper around [gmp] it will work equally well with [mpir]. Indeed use of [mpir]
is recommended on Win32.
* This backend supports rvalue-references and is move-aware, making instantiations of `number` on this backend move aware.
[h5 Example:]
[mpz_eg]
[endsect] [/section:gmp_int gmp_int]
[section:tom_int tom_int]
`#include `
namespace boost{ namespace multiprecision{
class tommath_int;
typedef number tom_int;
}} // namespaces
The `tommath_int` back-end is used via the typedef `boost::multiprecision::tom_int`. It acts as a thin wrapper around the [tommath] `tom_int`
to provide an integer type that is a drop-in replacement for the native C++ integer types, but with unlimited precision.
Things you should know when using this type:
* Default constructed objects have the value zero (this is [tommath]'s default behavior).
* Although `tom_int` is mostly a drop in replacement for the integer __fundamental_types, it should be noted that it is a
rather strange beast as it's a signed type that is not a 2's complement type. As a result the bitwise operations
`| & ^` will throw a `std::runtime_error` exception if either of the arguments is negative. Similarly the complement
operator`~` is deliberately not implemented for this type.
* Formatted IO for this type does not support octal or hexadecimal notation for negative values,
as a result performing formatted output on this type when the argument is negative and either of the flags
`std::ios_base::oct` or `std::ios_base::hex` are set, will result in a `std::runtime_error` will be thrown.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be interpreted
as a valid integer.
* Division by zero results in a `std::overflow_error` being thrown.
[h5 Example:]
[tommath_eg]
[endsect] [/section:tom_int tom_int]
[section:egs Examples]
[import ../example/integer_examples.cpp]
[section:factorials Factorials]
[FAC1]
[endsect] [/section:factorials Factorials]
[section:bitops Bit Operations]
[BITOPS]
[endsect] [/section:bitops Bit Operations]
[endsect]
[endsect]
[section:floats Floating-point Types]
The following back-ends provide floating-point arithmetic:
[table
[[Backend Type][Header][Radix][Dependencies][Pros][Cons]]
[[`cpp_bin_float`][boost/multiprecision/cpp_bin_float.hpp][2][None][Header only, all C++ implementation. Boost licence.][Approximately 2x slower than the [mpfr] or [gmp] libraries.]]
[[`cpp_dec_float`][boost/multiprecision/cpp_dec_float.hpp][10][None][Header only, all C++ implementation. Boost licence.][Approximately 2x slower than the [mpfr] or [gmp] libraries.]]
[[`mpf_float`][boost/multiprecision/gmp.hpp][2][[gmp]][Very fast and efficient back-end.][Dependency on GNU licensed [gmp] library.]]
[[`mpfr_float`][boost/multiprecision/mpfr.hpp][2][[gmp] and [mpfr]][Very fast and efficient back-end, with its own standard library implementation.][Dependency on GNU licensed [gmp] and [mpfr] libraries.]]
[[`float128`][boost/multiprecision/float128.hpp][2][Either [quadmath] or the Intel C++ Math library.][Very fast and efficient back-end for 128-bit floating-point values (113-bit mantissa, equivalent to FORTRAN's QUAD real)][Depends on the compiler being either recent GCC or Intel C++ versions.]]
]
[section:cpp_bin_float cpp_bin_float]
`#include `
namespace boost{ namespace multiprecision{
enum digit_base_type
{
digit_base_2 = 2,
digit_base_10 = 10
};
template
class cpp_bin_float;
typedef number > cpp_bin_float_50;
typedef number > cpp_bin_float_100;
typedef number, et_off> cpp_bin_float_single;
typedef number, et_off> cpp_bin_float_double;
typedef number, et_off> cpp_bin_float_double_extended;
typedef number, et_off> cpp_bin_float_quad;
typedef number, et_off> cpp_bin_float_oct;
}} // namespaces
The `cpp_bin_float` back-end is used in conjunction with `number`: It acts as an entirely C++ (header only and dependency free)
floating-point number type that is a drop-in replacement for the native C++ floating-point types, but with
much greater precision.
Type `cpp_bin_float` can be used at fixed precision by specifying a non-zero `Digits` template parameter.
The typedefs `cpp_bin_float_50` and `cpp_bin_float_100` provide arithmetic types at 50 and 100 decimal digits precision
respectively.
Optionally, you can specify whether the precision is specified in decimal digits or binary bits - for example
to declare a `cpp_bin_float` with exactly the same precision as `double` one would use
`number >`. The typedefs `cpp_bin_float_single`, `cpp_bin_float_double`,
`cpp_bin_float_quad`, `cpp_bin_float_oct` and `cpp_bin_float_double_extended` provide
software analogues of the IEEE single, double, quad and octuple float data types, plus the Intel-extended-double type respectively.
Note that while these types are functionally equivalent to the native IEEE types, but they do not have the same size
or bit-layout as true IEEE compatible types.
Normally `cpp_bin_float` allocates no memory: all of the space required for its digits are allocated
directly within the class. As a result care should be taken not to use the class with too high a digit count
as stack space requirements can grow out of control. If that represents a problem then providing an allocator
as a template parameter causes `cpp_bin_float` to dynamically allocate the memory it needs: this
significantly reduces the size of `cpp_bin_float` and increases the viable upper limit on the number of digits
at the expense of performance. However, please bear in mind that arithmetic operations rapidly become ['very] expensive
as the digit count grows: the current implementation really isn't optimized or designed for large digit counts.
Note that since the actual type of the objects allocated
is completely opaque, the suggestion would be to use an allocator with `void` `value_type`, for example:
`number > >`.
The final template parameters determine the type and range of the exponent: parameter `Exponent` can be
any signed integer type, but note that `MinExponent` and `MaxExponent` can not go right up to the limits
of the `Exponent` type as there has to be a little extra headroom for internal calculations. You will
get a compile time error if this is the case. In addition if MinExponent or MaxExponent are zero, then
the library will choose suitable values that are as large as possible given the constraints of the type
and need for extra headroom for internal calculations.
There is full standard library and `numeric_limits` support available for this type.
Things you should know when using this type:
* Default constructed `cpp_bin_float`s have a value of zero.
* The radix of this type is 2, even when the precision is specified as decimal digits.
* The type supports both infinities and NaNs. An infinity is generated whenever the result would overflow,
and a NaN is generated for any mathematically undefined operation.
* There is a `std::numeric_limits` specialisation for this type.
* Any `number` instantiated on this type, is convertible to any other `number` instantiated on this type -
for example you can convert from `number >` to `number >`.
Narrowing conversions round to nearest and are `explicit`.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be interpreted
as a valid floating-point number.
* All arithmetic operations are correctly rounded to nearest. String conversions and the `sqrt` function
are also correctly rounded, but transcendental functions (sin, cos, pow, exp etc) are not.
[h5 cpp_bin_float example:]
[cpp_bin_float_eg]
[endsect]
[section:cpp_dec_float cpp_dec_float]
`#include `
namespace boost{ namespace multiprecision{
template
class cpp_dec_float;
typedef number > cpp_dec_float_50;
typedef number > cpp_dec_float_100;
}} // namespaces
The `cpp_dec_float` back-end is used in conjunction with `number`: It acts as an entirely C++ (header only and dependency free)
floating-point number type that is a drop-in replacement for the native C++ floating-point types, but with
much greater precision.
Type `cpp_dec_float` can be used at fixed precision by specifying a non-zero `Digits10` template parameter.
The typedefs `cpp_dec_float_50` and `cpp_dec_float_100` provide arithmetic types at 50 and 100 decimal digits precision
respectively. Optionally, you can specify an integer type to use for the exponent, this defaults to a 32-bit integer type
which is more than large enough for the vast majority of use cases, but larger types such as `long long` can also be specified
if you need a truly huge exponent range. In any case the ExponentType must be a __fundamental signed integer type at least 2 bytes
and 16-bits wide.
Normally `cpp_dec_float` allocates no memory: all of the space required for its digits are allocated
directly within the class. As a result care should be taken not to use the class with too high a digit count
as stack space requirements can grow out of control. If that represents a problem then providing an allocator
as the final template parameter causes `cpp_dec_float` to dynamically allocate the memory it needs: this
significantly reduces the size of `cpp_dec_float` and increases the viable upper limit on the number of digits
at the expense of performance. However, please bear in mind that arithmetic operations rapidly become ['very] expensive
as the digit count grows: the current implementation really isn't optimized or designed for large digit counts.
There is full standard library and `std::numeric_limits` support available for this type.
Things you should know when using this type:
* Default constructed `cpp_dec_float`s have a value of zero.
* The radix of this type is 10. As a result it can behave subtly differently from base-2 types.
* The type has a number of internal guard digits over and above those specified in the template argument.
Normally these should not be visible to the user.
* The type supports both infinities and NaNs. An infinity is generated whenever the result would overflow,
and a NaN is generated for any mathematically undefined operation.
* There is a `std::numeric_limits` specialisation for this type.
* Any `number` instantiated on this type, is convertible to any other `number` instantiated on this type -
for example you can convert from `number >` to `number >`.
Narrowing conversions are truncating and `explicit`.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be interpreted
as a valid floating-point number.
* The actual precision of a `cpp_dec_float` is always slightly higher than the number of digits specified in
the template parameter, actually how much higher is an implementation detail but is always at least 8 decimal
digits.
* Operations involving `cpp_dec_float` are always truncating. However, note that since there are guard digits
in effect, in practice this has no real impact on accuracy for most use cases.
[h5 cpp_dec_float example:]
[cpp_dec_float_eg]
[endsect]
[section:gmp_float gmp_float]
`#include `
namespace boost{ namespace multiprecision{
template
class gmp_float;
typedef number > mpf_float_50;
typedef number > mpf_float_100;
typedef number > mpf_float_500;
typedef number > mpf_float_1000;
typedef number > mpf_float;
}} // namespaces
The `gmp_float` back-end is used in conjunction with `number` : it acts as a thin wrapper around the [gmp] `mpf_t`
to provide an real-number type that is a drop-in replacement for the native C++ floating-point types, but with
much greater precision.
Type `gmp_float` can be used at fixed precision by specifying a non-zero `Digits10` template parameter, or
at variable precision by setting the template argument to zero. The typedefs mpf_float_50, mpf_float_100,
mpf_float_500, mpf_float_1000 provide arithmetic types at 50, 100, 500 and 1000 decimal digits precision
respectively. The typedef mpf_float provides a variable precision type whose precision can be controlled via the
`number`s member functions.
[note This type only provides standard library and `numeric_limits` support when the precision is fixed at compile time.]
As well as the usual conversions from arithmetic and string types, instances of `number >` are
copy constructible and assignable from:
* The [gmp] native types `mpf_t`, `mpz_t`, `mpq_t`.
* The `number` wrappers around those types: `number >`, `number`, `number`.
It's also possible to access the underlying `mpf_t` via the `data()` member function of `gmp_float`.
Things you should know when using this type:
* Default constructed `gmp_float`s have the value zero (this is the [gmp] library's default behavior).
* No changes are made to the [gmp] library's global settings, so this type can be safely mixed with
existing [gmp] code.
* This backend supports rvalue-references and is move-aware, making instantiations of `number` on this backend move aware.
* It is not possible to round-trip objects of this type to and from a string and get back
exactly the same value. This appears to be a limitation of [gmp].
* Since the underlying [gmp] types have no notion of infinities or NaNs, care should be taken
to avoid numeric overflow or division by zero. That latter will result in a std::overflow_error being thrown,
while generating excessively large exponents may result in instability of the underlying [gmp]
library (in testing, converting a number with an excessively large or small exponent
to a string caused [gmp] to segfault).
* This type can equally be used with [mpir] as the underlying implementation - indeed that is
the recommended option on Win32.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be interpreted
as a valid floating-point number.
* Division by zero results in a `std::overflow_error` being thrown.
[h5 [gmp] example:]
[mpf_eg]
[endsect]
[section:mpfr_float mpfr_float]
`#include `
namespace boost{ namespace multiprecision{
enum mpfr_allocation_type
{
allocate_stack,
allocate_dynamic
};
template
class mpfr_float_backend;
typedef number > mpfr_float_50;
typedef number > mpfr_float_100;
typedef number > mpfr_float_500;
typedef number > mpfr_float_1000;
typedef number > mpfr_float;
typedef number > static_mpfr_float_50;
typedef number > static_mpfr_float_100;
}} // namespaces
The `mpfr_float_backend` type is used in conjunction with `number`: It acts as a thin wrapper around the [mpfr] `mpfr_t`
to provide an real-number type that is a drop-in replacement for the native C++ floating-point types, but with
much greater precision.
Type `mpfr_float_backend` can be used at fixed precision by specifying a non-zero `Digits10` template parameter, or
at variable precision by setting the template argument to zero. The typedefs mpfr_float_50, mpfr_float_100,
mpfr_float_500, mpfr_float_1000 provide arithmetic types at 50, 100, 500 and 1000 decimal digits precision
respectively. The typedef mpfr_float provides a variable precision type whose precision can be controlled via the
`number`s member functions.
In addition the second template parameter lets you choose between dynamic allocation (the default,
and uses MPFR's normal allocation routines),
or stack allocation (where all the memory required for the underlying data types is stored
within `mpfr_float_backend`). The latter option can result in significantly faster code, at the
expense of growing the size of `mpfr_float_backend`. It can only be used at ['fixed precision], and
should only be used for lower digit counts. Note that we can not guarantee that using `allocate_stack`
won't cause any calls to `mpfr`'s allocation routines, as `mpfr` may call these inside its own code.
The following table gives an idea of the performance tradeoff's at 50 decimal digits
precision[footnote Compiled with VC++10 and /Ox, with MPFR-3.0.0 and MPIR-2.3.0]:
[table
[[Type][Bessel function evaluation, relative times]]
[[`number, et_on>`][1.0 (5.5s)]]
[[`number, et_off>`][1.05 (5.8s)]]
[[`number, et_on>`][1.05 (5.8s)]]
[[`number, et_off>`][1.16 (6.4s)]]
]
[note This type only provides `numeric_limits` support when the precision is fixed at compile time.]
As well as the usual conversions from arithmetic and string types, instances of `number >` are
copy constructible and assignable from:
* The [gmp] native types `mpf_t`, `mpz_t`, `mpq_t`.
* The [mpfr] native type `mpfr_t`.
* The `number` wrappers around those types: `number >`, `number >`, `number`, `number`.
It's also possible to access the underlying `mpfr_t` via the data() member function of `mpfr_float_backend`.
Things you should know when using this type:
* A default constructed `mpfr_float_backend` is set to zero (['Note that this is [*not] the default [mpfr] behavior]).
* All operations use round to nearest.
* No changes are made to [gmp] or [mpfr] global settings, so this type can coexist with existing
[mpfr] or [gmp] code.
* The code can equally use [mpir] in place of [gmp] - indeed that is the preferred option on Win32.
* This backend supports rvalue-references and is move-aware, making instantiations of `number` on this backend move aware.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be interpreted
as a valid floating-point number.
* Division by zero results in an infinity.
* When using the variable precision type `mpfr_float`, then copy construction and assignment ['copies the precision
of the source variable]. Likewise move construction and assignment.
* When constructing the variable precision type `mpfr_float` you can specify two arguments to the constructor - the first
is the value to assign to the variable, the second is an unsigned integer specifying the precision in decimal places. The
`assign` member function similarly has a 2-argument overload taking the value to assign and the precision. You can use this
to preserve the precision of the target variable using the somewhat arcane: `a.assign(b, a.precision())`, which assigns `b` to `a`
but preserves the precision of `a`.
[h5 [mpfr] example:]
[mpfr_eg]
[endsect] [/section:mpfr_float mpfr_float]
[section:float128 float128]
`#include `
namespace boost{ namespace multiprecision{
class float128_backend;
typedef number float128;
}} // namespaces
The `float128` number type is a very thin wrapper around GCC's `__float128` or Intel's `_Quad` data types
and provides an real-number type that is a drop-in replacement for the native C++ floating-point types, but with
a 113 bit mantissa, and compatible with FORTRAN's 128-bit QUAD real.
All the usual standard library and `std::numeric_limits` support are available, performance should be equivalent
to the underlying native types: for example the LINPACK benchmarks for GCC's `__float128` and
`boost::multiprecision::float128` both achieved 5.6 MFLOPS[footnote On 64-bit Ubuntu 11.10, GCC-4.8.0, Intel Core 2 Duo T5800.].
As well as the usual conversions from arithmetic and string types, instances of `float128` are
copy constructible and assignable from GCC's `__float128` and Intel's `_Quad` data types.
It's also possible to access the underlying `__float128` or `_Quad` type via the `data()` member
function of `float128_backend`.
Things you should know when using this type:
* Default constructed `float128`s have the value zero.
* This backend supports rvalue-references and is move-aware, making instantiations of `number` on this backend move aware.
* This type is fully `constexpr` aware - basic constexpr arithmetic is supported from C++14 and onwards, comparisons,
plus the functions `fabs`, `abs`, `fpclassify`, `isnormal`, `isfinite`, `isinf` and `isnan` are also supported if either
the compiler implements C++20's `std::is_constant_evaluated()`, or if the compiler is GCC.
* It is not possible to round-trip objects of this type to and from a string and get back
exactly the same value when compiled with Intel's C++ compiler and using `_Quad` as the underlying type: this is a current limitation of
our code. Round tripping when using `__float128` as the underlying type is possible (both for GCC and Intel).
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be interpreted
as a valid floating-point number.
* Division by zero results in an infinity being produced.
* Type `float128` can be used as a literal type (constexpr support).
* Type `float128` can be used for full `constexpr` arithmetic from C++14 and later with GCC. The functions `abs`, `fabs`,
`fpclassify`, `isnan`, `isinf`, `isfinite` and `isnormal` are also `constexpr`, but the transcendental functions are not.
* When using the Intel compiler, the underlying type defaults to `__float128` if it's available and `_Quad` if not. You can override
the default by defining either `BOOST_MP_USE_FLOAT128` or `BOOST_MP_USE_QUAD`.
* When the underlying type is Intel's `_Quad` type, the code must be compiled with the compiler option `-Qoption,cpp,--extended_float_type`.
* When compiling with `gcc`, you need to use the flag `--std=gnu++11/14/17`, as the suffix 'Q' is a GNU extension. Compilation fails with the flag `--std=c++11/14/17`
unless you also use `-fext-numeric-literals`.
* You will need to link to `libquadmath.dll` with the link command `-lquadmath` and ensure that the DLL is visible by the linker.
If you are using the B2/bjam build system then commands`-lQUADMATH` and `-L"path/to/lib"` will be needed.
* The values shown by `std::numeric_limits` and extremely close ['but not identical]
to those from the equivalent precision and range multiprecision types `std::numeric_limits` and `std::numeric_limits`.
[h5 float128 example:]
[float128_eg]
Values for `std::numeric_limits` are:
[float128_numeric_limits]
[endsect] [/section:float128 float128]
[section:fp_eg Examples]
[import ../example/floating_point_examples.cpp]
[section:aos Area of Circle]
[/I:\boost\libs\multiprecision\example\floating_point_examples.cpp]
[AOS1]
[AOS2]
[AOS3]
[endsect] [/section:aos Area of Circle]
[section:caveats Drop-in Caveats]
[import ../example/big_seventh.cpp]
[big_seventh_example_1]
[big_seventh_example_2]
[big_seventh_example_3]
[big_seventh_example_constexpr] [/ Hopefully a temporary restriction.]
[big_seventh_example_4]
Typical output is:
[big_seventh_example_output]
[endsect] [/section:caveats Caveats]
[section:jel Defining a Special Function.]
[JEL]
[endsect] [/section:jel Defining a Special Function.]
[section:nd Calculating a Derivative]
[ND1]
[ND2]
[ND3]
[endsect] [/section:nd Calculating a Derivative]
[section:gi Calculating an Integral]
[GI1]
[GI2]
[endsect] [/section:gi Calculating an Integral]
[section:poly_eg Polynomial Evaluation]
[POLY]
[endsect] [/section:poly_eg Polynomial Evaluation]
[section:variable_precision Variable-Precision Newton Evaluation]
[mpfr_variable]
[endsect] [/section:variable_precision Variable-Precision Newton Evaluation]
[section:gauss_lagerre_quadrature Gauss-Laguerre quadrature]
[import ../example/gauss_laguerre_quadrature.cpp]
This example uses __Boost_Multiprecision to implement a high-precision Gauss-Laguerre quadrature integration.
The quadrature is used to calculate the `airy_ai(x)` function for real-valued `x` on the positive axis with `x >= 1`.
In this way, the integral representation could be seen as part of a scheme to calculate
real-valued Airy functions on the positive axis for medium to large argument.
A Taylor series or hypergeometric function (not part of this example) could be used for smaller arguments.
This example has been tested with decimal digits counts ranging from 21...301, by adjusting the parameter
`local::my_digits10` at compile time.
The quadrature integral representaion of `airy_ai(x)` used in this example can be found in:
A. Gil, J. Segura, N.M. Temme, "Numerical Methods for Special Functions"
(SIAM Press 2007), ISBN 9780898717822, Sect. 5.3.3, in particular Eq. 5.110, page 145.
Subsequently, Gil et al's book cites the another work:
W. Gautschi, "Computation of Bessel and Airy functions and of related Gaussian quadrature formulae",
BIT, 42 (2002), pp. 110-118, [@https://doi.org/10.1023/A:1021974203359] that is also available as
[@https://www.cs.purdue.edu/homes/wxg/selected_works/section_02/169.pdf Gautschi_169.pdf].
This Gauss-Laguerre quadrature is designed for `airy_ai(x)` with real-valued `x >= 1`.
The example uses Gauss-Laguerre quadrature integration to compute `airy_ai(x / 7)`
with `7 <= x <= 120` and where `x` is incremented in steps of 1.
During development of this example, we have empirically found the numbers of Gauss-Laguerre coefficients
needed for convergence when using various counts of base-10 digits.
Let's calibrate, for instance, the number of coefficients needed at the point `x = 1`.
Empirical data were used with __WolframAlpha :
``
Fit[{{21.0, 3.5}, {51.0, 11.1}, {101.0, 22.5}, {201.0, 46.8}}, {1, d, d^2}, d]FullSimplify[%]
0.0000178915 d^2 + 0.235487 d - 1.28301
or
-1.28301 + (0.235487 + 0.0000178915 d) d
``
We need significantly more coefficients at smaller real values than are needed
at larger real values because the slope derivative of `airy_ai(x)` gets more
steep as x approaches zero. `laguerre_order` is calculated using this equation.
Snippets from (copious) output from a progress bar during calculation of approximate root estimates
followed by calculation of accurate abscissa and weights is:
[gauss_laguerre_quadrature_output_1]
Finally the result using Gauss-Laguerre quadrature is compared with a calculation using `cyl_bessel_k`,
and both are listed, finally confirming that none differ more than a small tolerance.
[gauss_laguerre_quadrature_output_2]
For more detail see comments in the source code for this example at [@../../example/gauss_laguerre_quadrature.cpp gauss_laguerre_quadrature.cpp].
[endsect] [/section:gauss_lagerre_quadrature Gauss-Laguerre quadrature]
[endsect] [/section:fp_eg Examples]
[endsect] [/section:floats floating-point Numbers]
[section:interval Interval Number Types]
There is one currently only one interval number type supported - [mpfi].
[section:mpfi mpfi_float]
`#include `
namespace boost{ namespace multiprecision{
template
class mpfi_float_backend;
typedef number > mpfi_float_50;
typedef number > mpfifloat_100;
typedef number > mpfifloat_500;
typedef number > mpfi_float_1000;
typedef number > mpfi_float;
}} // namespaces
The `mpfi_float_backend` type is used in conjunction with `number`: It acts as a thin wrapper around the [mpfi] `mpfi_t`
to provide an real-number type that is a drop-in replacement for the native C++ floating-point types, but with
much greater precision and implementing interval arithmetic.
Type `mpfi_float_backend` can be used at fixed precision by specifying a non-zero `Digits10` template parameter, or
at variable precision by setting the template argument to zero. The `typedef`s `mpfi_float_50`, `mpfi_float_100`,
`mpfi_float_500`, `mpfi_float_1000` provide arithmetic types at 50, 100, 500 and 1000 decimal digits precision
respectively. The `typedef mpfi_float` provides a variable precision type whose precision can be controlled via theF
`number`s member functions.
[note This type only provides `numeric_limits` support when the precision is fixed at compile time.]
As well as the usual conversions from arithmetic and string types, instances of `number >` are
copy constructible and assignable from:
* The [mpfi] native type `mpfi_t`.
* The `number` wrappers around [mpfi] or [mpfr]: `number >` and `number >`.
* There is a two argument constructor taking two `number >` arguments specifying the interval.
It's also possible to access the underlying `mpfi_t` via the `data()` member function of `mpfi_float_backend`.
Things you should know when using this type:
* A default constructed `mpfi_float_backend` is set to zero (['Note that this is [*not] the default [mpfi] behavior]).
* No changes are made to [gmp] or [mpfr] global settings, so this type can coexist with existing
[mpfr] or [gmp] code.
* The code can equally use [mpir] in place of [gmp] - indeed that is the preferred option on Win32.
* This backend supports rvalue-references and is move-aware, making instantiations of `number` on this backend move aware.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be interpreted
as a valid floating-point number.
* Division by zero results in an infinity.
There are some additional non member functions for working on intervals:
template
number, ExpressionTemplates> lower(const number, ExpressionTemplates>& val);
Returns the lower end of the interval.
template
number, ExpressionTemplates> upper(const number, ExpressionTemplates>& val);
Returns the upper end of the interval.
template
number, ExpressionTemplates> median(const number, ExpressionTemplates>& val);
Returns the mid point of the interval.
template
number, ExpressionTemplates> width(const number, ExpressionTemplates>& val);
Returns the absolute width of the interval.
template
number, ExpressionTemplates> intersect(
const number, ExpressionTemplates>& a,
const number, ExpressionTemplates>& b);
Returns the interval which is the intersection of the ['a] and ['b]. Returns an
unspecified empty interval if there is no such intersection.
template
number, ExpressionTemplates> hull(
const number, ExpressionTemplates>& a,
const number, ExpressionTemplates>& b);
Returns the interval which is the union of ['a] and ['b].
template
bool overlap(const number, ExpressionTemplates>& a,
const number, ExpressionTemplates>& b);
Returns `true` only if the intervals ['a] and ['b] overlap.
template
bool in(const number, ExpressionTemplates1>& a,
const number, ExpressionTemplates2>& b);
Returns `true` only if point ['a] is contained within the interval ['b].
template
bool zero_in(const number, ExpressionTemplates>& a);
Returns `true` only if the interval ['a] contains the value zero.
template
bool subset(const number, ExpressionTemplates>& a,
const number, ExpressionTemplates>& b);
Returns `true` only if ['a] is a subset of ['b].
template
bool proper_subset(const number, ExpressionTemplates>& a,
const number, ExpressionTemplates>& b);
Returns `true` only if ['a] is a proper subset of ['b].
template
bool empty(const number, ExpressionTemplates>& a);
Returns `true` only if ['a] is an empty interval, equivalent to `upper(a) < lower(a)`.
template
bool singleton(const number, ExpressionTemplates>& a);
Returns `true` if `lower(a) == upper(a)`.
[h5 [mpfi] example:]
[mpfi_eg]
[endsect] [ section:mpfi mpfi_float]
[endsect] [/section:interval Interval Number Types]
[section:complex Complex Number Types]
The following backends provide complex number arithmetic:
[table
[[Backend Type][Header][Radix][Dependencies][Pros][Cons]]
[[`cpp_complex`][boost/multiprecision/cpp_complex.hpp][2][None][An all C++ Boost-licensed implementation.][Slower than [mpc].]]
[[`mpc`][boost/multiprecision/mpc.hpp][2][[mpc]][Very fast and efficient back-end.][Dependency on LGLP-licensed [MPC] library.]]
[[`compplex128`][boost/multiprecision/complex128.hpp][2][`__float128` and libquadmath][Very fast and efficient number type.][128-bit precision only, and resticted to GCC.]]
[[`complex_adaptor`][boost/multiprecision/complex_adaptor.hpp][-][none][Can convert any backend type into a complex number backend.][Not a number in its own right, and hard to use as a result.]]
]
[section:cpp_complex cpp_complex]
`#include `
namespace boost{ namespace multiprecision{
template
using cpp_complex_backend = complex_adaptor >;
template
using cpp_complex = number >, ExpressionTemplates>;
typedef cpp_complex<50> cpp_complex_50;
typedef cpp_complex<100> cpp_complex_100;
typedef cpp_complex<24, backends::digit_base_2, void, boost::int16_t, -126, 127> cpp_complex_single;
typedef cpp_complex<53, backends::digit_base_2, void, boost::int16_t, -1022, 1023> cpp_complex_double;
typedef cpp_complex<64, backends::digit_base_2, void, boost::int16_t, -16382, 16383> cpp_complex_extended;
typedef cpp_complex<113, backends::digit_base_2, void, boost::int16_t, -16382, 16383> cpp_complex_quad;
typedef cpp_complex<237, backends::digit_base_2, void, boost::int32_t, -262142, 262143> cpp_complex_oct;
}} // namespaces
The `cpp_complex_backend` back-end is used in conjunction with `number`: It acts as an entirely C++ (header only and dependency free)
complex number type that is a drop-in replacement for `std::complex`, but with much greater precision.
The template alias `cpp_complex` avoids the need to use class `number` directly.
Type `cpp_complex` can be used at fixed precision by specifying a non-zero `Digits` template parameter.
The typedefs `cpp_complex_50` and `cpp_complex_100` provide complex number types at 50 and 100 decimal digits precision
respectively.
Optionally, you can specify whether the precision is specified in decimal digits or binary bits - for example
to declare a `cpp_complex` with exactly the same precision as `std::complex` one would use
`cpp_complex<53, digit_base_2>`. The typedefs `cpp_complex_single`, `cpp_complex_double`,
`cpp_complex_quad`, `cpp_complex_oct` and `cpp_complex_double_extended` provide
software analogues of the IEEE single, double, quad and octuple float data types, plus the Intel-extended-double type respectively.
Note that while these types are functionally equivalent to the native IEEE types, but they do not have the same size
or bit-layout as true IEEE compatible types.
Normally `cpp_complex` allocates no memory: all of the space required for its digits are allocated
directly within the class. As a result care should be taken not to use the class with too high a digit count
as stack space requirements can grow out of control. If that represents a problem then providing an allocator
as a template parameter causes `cpp_complex` to dynamically allocate the memory it needs: this
significantly reduces the size of `cpp_complex` and increases the viable upper limit on the number of digits
at the expense of performance. However, please bear in mind that arithmetic operations rapidly become ['very] expensive
as the digit count grows: the current implementation really isn't optimized or designed for large digit counts.
Note that since the actual type of the objects allocated
is completely opaque, the suggestion would be to use an allocator with `char` `value_type`, for example:
`cpp_complex<1000, digit_base_10, std::allocator >`.
The next template parameters determine the type and range of the exponent: parameter `Exponent` can be
any signed integer type, but note that `MinExponent` and `MaxExponent` can not go right up to the limits
of the `Exponent` type as there has to be a little extra headroom for internal calculations. You will
get a compile time error if this is the case. In addition if MinExponent or MaxExponent are zero, then
the library will choose suitable values that are as large as possible given the constraints of the type
and need for extra headroom for internal calculations.
Finally, as with class `number`, the final template parameter determines whether expression templates are turn
on or not. Since by default this type allocates no memory, expression template support is off by default.
However, you should probably turn it on if you specify an allocator.
There is full standard library support available for this type, comparable with what `std::complex` provides.
Things you should know when using this type:
* Default constructed `cpp_complex`s have a value of zero.
* The radix of this type is 2, even when the precision is specified as decimal digits.
* The type supports both infinities and NaNs. An infinity is generated whenever the result would overflow,
and a NaN is generated for any mathematically undefined operation.
* There is no `std::numeric_limits` specialisation for this type: this is the same behaviour as `std::complex`. If you need
`std::numeric_limits` support you need to look at `std::numeric_limits`.
* Any `number` instantiated on this type, is convertible to any other `number` instantiated on this type -
for example you can convert from `number >` to `number >`.
Narrowing conversions round to nearest and are `explicit`.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be interpreted
as a valid complex number.
[h5 example:]
[cpp_complex_eg]
Which produces the output (for the multiprecision type):
[cpp_complex_out]
[endsect] [/section:complex Complex Number Types]
[section:mpc_complex mpc_complex]
`#include `
namespace boost{ namespace multiprecision{
template
class mpc_complex_backend;
typedef number > mpc_complex_50;
typedef number > mpc_complex_100;
typedef number > mpc_complex_500;
typedef number > mpc_complex_1000;
typedef number > mpc_complex;
}} // namespaces
The `mpc_complex_backend` type is used in conjunction with `number`: It acts as a thin wrapper around the [mpc] `mpc_t`
to provide an real-number type that is a drop-in replacement for `std::complex`, but with
much greater precision.
Type `mpc_complex_backend` can be used at fixed precision by specifying a non-zero `Digits10` template parameter, or
at variable precision by setting the template argument to zero. The typedefs mpc_complex_50, mpc_complex_100,
mpc_complex_500, mpc_complex_1000 provide complex types at 50, 100, 500 and 1000 decimal digits precision
respectively. The typedef mpc_complex provides a variable precision type whose precision can be controlled via the
`number`s member functions.
The `mpc` backend should allow use of the same syntax as the C++ standard library complex type.
When using this backend, remember to link with the flags `-lmpc -lmpfr -lgmp`.
As well as the usual conversions from arithmetic and string types, instances of `number >` are
copy constructible and assignable from:
* The [gmp] native types `mpf_t`, `mpz_t`, `mpq_t`.
* The [mpfr] native type `mpfr_t`.
* The [mpc] native type `mpc_t`.
* The `number` wrappers around those types: `number >`, `number >`, `number`, `number`.
It's also possible to access the underlying `mpc_t` via the `data()` member function of `mpfr_float_backend`.
Things you should know when using this type:
* A default constructed `mpc_complex_backend` is set to zero (['Note that this is [*not] the default [mpc] behavior]).
* All operations use round to nearest.
* No changes are made to [mpc], [gmp] or [mpfr] global settings, so this type can coexist with existing
[mpc], [mpfr] or [gmp] code.
* The code can equally use [mpir] in place of [gmp] - indeed that is the preferred option on Win32.
* This backend supports rvalue-references and is move-aware, making instantiations of `number` on this backend move aware.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be interpreted
as a valid complex number.
* Division by zero results in a complex-infinity.
* Unlike `std::complex`, you can not use `reinterpret_cast` to treat this type as an array of the underlying floating point type.
* Unlike `std::complex`, there are no literals for imaginary values.
* When using the variable precision type `mpc_complex`, then copy construction and assignment ['copies the precision
of the source variable]. Likewise move construction and assignment.
* When constructing the variable precision type `mpc_complex` you can specify two arguments to the constructor - the first
is the value to assign to the variable, the second is an unsigned integer specifying the precision in decimal places. The
`assign` member function similarly has a 2-argument overload taking the value to assign and the precision. You can use this
to preserve the precision of the target variable using the somewhat arcane: `a.assign(b, a.precision())`, which assigns `b` to `a`
but preserves the precision of `a`.
[h5 [mpc] example:]
[mpc_eg]
Which produces the output (for the multiprecision type):
[mpc_out]
[endsect] [/section:mpc_complex mpc_complex]
[section:complex128 complex128]
`#include `
namespace boost{ namespace multiprecision{
class complex128_backend;
typedef number complex128;
}} // namespaces
The `complex128` number type is a very thin wrapper around GCC's `__float128` or Intel's `_Quad` data types
and provides a complex-number type that is a drop-in replacement for the native C++ floating-point types, but with
a 113 bit mantissa, and compatible with FORTRAN's 128-bit QUAD real.
All the usual standard library functions are available, performance should be equivalent
to the underlying native types.
As well as the usual conversions from arithmetic and string types, instances of `float128` are
copy constructible and assignable from GCC's `__float128` and Intel's `_Quad` data types.
Things you should know when using this type:
* Default constructed `complex128`s have the value zero.
* This backend supports rvalue-references and is move-aware, making instantiations of `number` on this backend move aware.
* It is not possible to round-trip objects of this type to and from a string and get back
exactly the same value when compiled with Intel's C++ compiler and using `_Quad` as the underlying type: this is a current limitation of
our code. Round tripping when using `__float128` as the underlying type is possible (both for GCC and Intel).
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be interpreted
as a valid floating-point number.
* Division by zero results in an infinity being produced.
* When using the Intel compiler, the underlying type defaults to `__float128` if it's available and `_Quad` if not. You can override
the default by defining either `BOOST_MP_USE_FLOAT128` or `BOOST_MP_USE_QUAD`.
* When the underlying type is Intel's `_Quad` type, the code must be compiled with the compiler option `-Qoption,cpp,--extended_float_type`.
[h5 complex128 example:]
[complex128_eg]
Which results in the output:
[complex128_out]
[endsect] [/section:complex128 complex128]
[section:complex_adaptor complex_adaptor]
namespace boost{ namespace multiprecision{
template
struct complex_adaptor;
}}
Class template `complex_adaptor` is designed to sit inbetween class `number` and an actual floating point backend,
in order to create a new complex number type.
It is the means by which we implement __cpp_complex and __complex128.
[endsect] [/section:complex_adaptor complex_adaptor]
[endsect] [/section:complex Complex Number Types]
[section:rational Rational Number Types]
The following back-ends provide rational number arithmetic:
[table
[[Backend Type][Header][Radix][Dependencies][Pros][Cons]]
[[`cpp_rational`][boost/multiprecision/cpp_int.hpp][2][None][An all C++ Boost-licensed implementation.][Slower than [gmp].]]
[[`gmp_rational`][boost/multiprecision/gmp.hpp][2][[gmp]][Very fast and efficient back-end.][Dependency on GNU licensed [gmp] library.]]
[[`tommath_rational`][boost/multiprecision/tommath.hpp][2][[tommath]][All C/C++ implementation that's Boost Software Licence compatible.][Slower than [gmp].]]
[[`rational_adaptor`][boost/multiprecision/rational_adaptor.hpp][N/A][none][All C++ adaptor that allows any integer back-end type to be used as a rational type.][Requires an underlying integer back-end type.]]
[[`boost::rational`][boost/rational.hpp][N/A][None][A C++ rational number type that can used with any `number` integer type.][The expression templates used by `number` end up being "hidden" inside `boost::rational`: performance may well suffer as a result.]]
]
[section:cpp_rational cpp_rational]
`#include `
namespace boost{ namespace multiprecision{
typedef rational_adaptor > cpp_rational_backend;
typedef number 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:
* Default constructed `cpp_rational`s have the value zero.
* Division by zero results in a `std::overflow_error` being thrown.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be
interpreted as a valid rational number.
[h5 Example:]
[cpp_rational_eg]
[endsect] [/section:rational Rational Number Types]
[section:gmp_rational gmp_rational]
`#include `
namespace boost{ namespace multiprecision{
class gmp_rational;
typedef number mpq_rational;
}} // namespaces
The `gmp_rational` back-end is used via the typedef `boost::multiprecision::mpq_rational`. It acts as a thin wrapper around the [gmp] `mpq_t`
to provide 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 `number` are copy constructible
and assignable from:
* The [gmp] native types: `mpz_t`, `mpq_t`.
* `number`.
There is also a two-argument constructor that accepts a numerator and denominator (both of type `number`).
There are also non-member functions:
mpz_int numerator(const mpq_rational&);
mpz_int denominator(const mpq_rational&);
which return the numerator and denominator of the number.
It's also possible to access the underlying `mpq_t` via the `data()` member function of `mpq_rational`.
Things you should know when using this type:
* Default constructed `mpq_rational`s have the value zero (this is the [gmp] default behavior).
* Division by zero results in a `std::overflow_error` being thrown.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be
interpreted as a valid rational number.
* No changes are made to the [gmp] library's global settings, so this type can coexist with existing
[gmp] code.
* The code can equally be used with [mpir] as the underlying library - indeed that is the preferred option on Win32.
[h5 Example:]
[mpq_eg]
[endsect] [/section:gmp_rational gmp_rational]
[section:tommath_rational tommath_rational]
`#include `
namespace boost{ namespace multiprecision{
typedef rational_adpater tommath_rational;
typedef number 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`
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` 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:
* Default constructed `tom_rational`s have the value zero (this the inherited Boost.Rational behavior).
* Division by zero results in a `std::overflow_error` being thrown.
* Conversion from a string results in a `std::runtime_error` being thrown if the string can not be
interpreted as a valid rational number.
* No changes are made to [tommath]'s global state, so this type can safely coexist with other [tommath] code.
* Performance of this type has been found to be pretty poor - this need further investigation - but it appears that Boost.Rational
needs some improvement in this area.
[h5 Example:]
[mp_rat_eg]
[endsect] [/section:tommath_rational tommath_rational]
[section:br Use With Boost.Rational]
All of the integer types in this library can be used as template arguments to `boost::rational`.
Note that using the library in this way largely negates the effect of the expression templates in `number`.
[endsect] [/section:br Use With Boost.Rational]
[section:rational_adaptor rational_adaptor]
namespace boost{ namespace multiprecision{
template
class rational_adpater;
}}
The class template `rational_adaptor` is a back-end for `number` which converts any existing integer back-end
into a rational-number back-end.
So for example, given an integer back-end type `MyIntegerBackend`, the use would be something like:
typedef number MyInt;
typedef number > MyRational;
MyRational r = 2;
r /= 3;
MyInt i = numerator(r);
assert(i == 2);
[endsect] [/section:rational_adaptor rational_adaptor]
[endsect] [/section:rational Rational Number Types]
[section:misc Miscellaneous Number Types.]
Backend types listed in this section are predominantly designed to aid debugging.
[section:logged_adaptor logged_adaptor]
`#include `
namespace boost{ namespace multiprecision{
template
void log_postfix_event(const Backend& result, const char* event_description);
template
void log_postfix_event(const Backend& result1, const T& result2, const char* event_description);
template
void log_prefix_event(const Backend& arg1, const char* event_description);
template
void log_prefix_event(const Backend& arg1, const T& arg2, const char* event_description);
template
void log_prefix_event(const Backend& arg1, const T& arg2, const U& arg3, const char* event_description);
template
void log_prefix_event(const Backend& arg1, const T& arg2, const U& arg3, const V& arg4, const char* event_description);
template
class logged_adaptor;
}} // namespaces
The `logged_adaptor` type is used in conjunction with `number` and some other backend type: it acts as a thin wrapper around
some other backend to class `number` and logs all the events that take place on that object. Before any number operation takes
place, it calls `log_prefix_event` with the arguments to the operation (up to 4), plus a string describing the operation.
Then after the operation it calls `log_postfix_event` with the result of the operation, plus a string describing the operation.
Optionally, `log_postfix_event` takes a second result argument: this occurs when the result of the operation is not a `number`,
for example when `fpclassify` is called, `log_postfix_event` will be called with `result1` being the argument to the function, and
`result2` being the integer result of `fpclassify`.
The default versions of `log_prefix_event` and `log_postfix_event` do nothing, it is therefore up to the user to overload these
for the particular backend being observed.
This type provides `numeric_limits` support whenever the template argument Backend does so.
This type is particularly useful when combined with an interval number type - in this case we can use `log_postfix_event`
to monitor the error accumulated after each operation. We could either set some kind of trap whenever the accumulated error
exceeds some threshold, or simply print out diagnostic information. Using this technique we can quickly locate the cause of
numerical instability in a particular routine. The following example demonstrates this technique in a trivial algorithm
that deliberately introduces cancellation error:
[logged_adaptor]
When we examine program output we can clearly see that the diameter of the interval increases after each subtraction:
[logged_adaptor_output]
[endsect] [/section:logged_adaptor logged_adaptor]
[section:debug_adaptor debug_adaptor]
`#include `
namespace boost{ namespace multiprecision{
template
class debug_adaptor;
}} // namespaces
The `debug_adaptor` type is used in conjunction with `number` and some other backend type: it acts as a thin wrapper around
some other backend to class `number` and intercepts all operations on that object storing the result as a string within itself.
This type provides `numeric_limits` support whenever the template argument Backend does so.
This type is particularly useful when your debugger provides a good view of `std::string`: when this is the case
multiprecision values can easily be inspected in the debugger by looking at the `debug_value` member of `debug_adaptor`.
The down side of this approach is that runtimes are much slower when using this type. Set against that it can make
debugging very much easier, certainly much easier than sprinkling code with `printf` statements.
When used in conjunction with the Visual C++ debugger visualisers, the value of a multiprecision type that uses this
backend is displayed in the debugger just a __fundamental value would be, here we're inspecting a value of type
`number > >`:
[$../debugger1.png]
Otherwise you will need to expand out the view and look at the "debug_value" member:
[$../debugger2.png]
It works for all the backend types equally too, here it is inspecting a `number >`:
[$../debugger3.png]
[endsect] [/section:debug_adaptor debug_adaptor]
[section:visualizers Visual C++ Debugger Visualizers]
Let's face it debugger multiprecision numbers is hard - simply because we can't easily inspect the value of the numbers.
Visual C++ provides a partial solution in the shape of "visualizers" which provide improved views of complex data structures,
these visualizers need to be added to the `[Visualizer]` section of `autoexp.dat` located in the `Common7/Packages/Debugger`
directory of your Visual Studio installation. The actual visualizer code is in the sandbox
[@https://svn.boost.org/svn/boost/sandbox/boost_docs/subprojects/DebuggerVisualizers/multiprecision.vis.txt here] - just cut and paste the code
into your `autoexp.dat` file.
[note These visualizers have only been tested with VC10, also given the ability of buggy visualizers to crash your Visual C++
debugger, make sure you back up `autoexp.dat` file before using these!!]
The first visualizer provides improved views of `debug_adaptor`:
[$../debugger1.png]
The next visualizer provides improved views of cpp_int: small numbers are displayed as actual values, while larger numbers are
displayed as an array of hexadecimal parts, with the most significant part first.
Here's what it looks like for small values:
[$../debugger4.png]
And for larger values:
[$../debugger5.png]
There is also a `~raw` child member that
lets you see the actual members of the class:
[$../debugger6.png]
The visualizer for `cpp_dec_float` shows the first few digits of the value in the preview field, and the full array of digits
when you expand the view. As before the `~raw` child gives you access to the actual data members:
[$../debugger7.png]
[endsect] [/section:visualizers Visual C++ Debugger Visualizers]
[endsect] [/section:misc Miscellaneous Number Types.]
[section:conversions Constructing and Interconverting Between Number Types]
All of the number types that are based on `number` have certain conversion rules in common.
In particular:
* Any number type can be constructed (or assigned) from any __fundamental arithmetic type, as long
as the conversion isn't lossy (for example float to int conversion):
cpp_dec_float_50 df(0.5); // OK construction from double
cpp_int i(450); // OK constructs from signed int
cpp_int j = 3.14; // Error, lossy conversion.
* A number can be explicitly constructed from an arithmetic type, even when the conversion is lossy:
cpp_int i(3.14); // OK explicit conversion
i = static_cast(3.14) // OK explicit conversion
i.assign(3.14); // OK, explicit assign and avoid a temporary from the cast above
i = 3.14; // Error, no implicit assignment operator for lossy conversion.
cpp_int j = 3.14; // Error, no implicit constructor for lossy conversion.
* A `number` can be converted to any __fundamental type, via the `convert_to` member function:
mpz_int z(2);
int i = z.convert_to(); // sets i to 2
* Conversions to rational numbers from floating-point ones are always allowed, and are exact and implicit
as long as the rational number uses an unbounded integer type. Please be aware that constructing a rational
number from an extended precision floating-point type with a large exponent range can effectively run the system
out of memory, as in the extreme case ['2[super max_exponent] / CHAR_BITS] bytes of storage may be required. This
does not represent a problem for __fundamental floating-point types however, as the exponent range for these is rather
limited.
* Conversions to floating-point numbers from rational ones are rounded to nearest (less than 0.5 __ULP error)
as long as the floating-point number is binary, and the integer type used by the rational number is unbounded.
Additional conversions may be supported by particular backends.
* A `number` can be converted to any __fundamental type, via an explicit conversion operator:
this functionality is only available on compilers supporting C++11's explicit conversion syntax.
mpz_int z(2);
int i = z; // Error, implicit conversion not allowed.
int j = static_cast(z); // OK explicit conversion.
* Any number type can be ['explicitly] constructed (or assigned) from a `const char*` or a `std::string`:
// pi to 50 places from a string:
cpp_dec_float_50 df("3.14159265358979323846264338327950288419716939937510");
// Integer type will automatically detect "0x" and "0" prefixes and parse the string accordingly:
cpp_int i("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000");
// Invalid input always results in a std::runtime_error being thrown:
i = static_cast("3.14");
// implicit conversions from strings are not allowed:
i = "23"; // Error, no assignment operator for implicit conversion from string
// assign member function, avoids having to create a temporary via a static_cast:
i.assign("23"); // OK
* Any number type will interoperate with the __fundamental types in arithmetic expressions as long as the conversions
are not lossy:
// pi to 50 places from a string:
cpp_dec_float_50 df = "3.14159265358979323846264338327950288419716939937510";
// Multiply by 2 - using an integer literal here is usually more efficient
// than constructing a temporary:
df *= 2;
// You can't mix integer types with floats though:
cpp_int i = 2;
i *= 3.14; // Error, no *= operator will be found.
* Any number type can be streamed to and from the C++ iostreams:
cpp_dec_float_50 df = "3.14159265358979323846264338327950288419716939937510";
// Now print at full precision:
std::cout << std::setprecision(std::numeric_limits::max_digits10)
<< df << std::endl
cpp_int i = 1;
i <<= 256;
// Now print in hex format with prefix:
std::cout << std::hex << std::showbase << i << std::endl;
* Interconversions between number types of the same family are allowed and are implicit conversions if no
loss of precision is involved, and explicit if it is:
int128_t i128 = 0;
int266_t i256 = i128; // OK implicit widening conversion
i128_t = i256; // Error, no assignment operator found, narrowing conversion is explicit.
i128_t = static_cast(i256); // OK, explicit narrowing conversion.
mpz_int z = 0;
mpf_float f = z; // OK, GMP handles this conversion natively, and it's not lossy and therefore implicit.
mpf_float_50 f50 = 2;
f = f50; // OK, conversion from fixed to variable precision, f will have 50 digits precision.
f50 = f; // Error, conversion from variable to fixed precision is potentially lossy, explicit cast required.
* Some interconversions between number types are completely generic, and are always available, albeit the conversions are always ['explicit]:
cpp_int cppi(2);
// We can always convert between numbers of the same category -
// int to int, rational to rational, or float to float, so this is OK
// as long as we use an explicit conversion:
mpz_int z(cppi);
// We can always promote from int to rational, int to float, or rational to float:
cpp_rational cppr(cppi); // OK, int to rational
cpp_dec_float_50 df(cppi); // OK, int to float
df = static_cast(cppr); // OK, explicit rational to float conversion
// However narrowing and/or implicit conversions always fail:
cppi = df; // Compiler error, conversion not allowed
* Other interconversions may be allowed as special cases, whenever the backend allows it:
mpf_t m; // Native GMP type.
mpf_init_set_ui(m, 0); // set to a value;
mpf_float i(m); // copies the value of the native type.
More information on what additional types a backend supports conversions from are given in the tutorial for each backend.
The converting constructor will be implicit if the backend's converting constructor is also implicit, and explicit if the
backends converting constructor is also explicit.
[endsect] [/section:conversions Constructing and Interconverting Between Number Types]
[section:random Generating Random Numbers]
Random numbers are generated in conjunction with Boost.Random.
There is a single generator that supports generating random integers with large bit counts:
[@http://www.boost.org/doc/html/boost/random/independent_bits_engine.html `independent_bits_engine`].
This type can be used with either ['unbounded] integer types, or with ['bounded] (ie fixed precision) unsigned integers:
[random_eg1]
Program output is:
[random_eg1_out]
In addition, the generator adaptors [@http://www.boost.org/doc/html/boost/random/discard_block_engine.html `discard_block`],
[@http://www.boost.org/doc/html/boost/random/xor_combine_engine.html `xor_combine_engine`] and
[@http://www.boost.org/doc/html/boost/random/discrete_distribution.html `discrete_distribution`] can be used
with multiprecision types. Note that if you seed an `independent_bits_engine`, then you are actually seeding
the underlying generator, and should therefore provide a sequence of unsigned 32-bit values as the seed.
Alternatively we can generate integers in a given range using
[@http://www.boost.org/doc/html/boost/random/uniform_int_distribution.html `uniform_int_distribution`], this will
invoke the underlying engine multiple times to build up the required number of bits in the result:
[random_eg2]
[random_eg2_out]
It is also possible to use [@http://www.boost.org/doc/html/boost/random/uniform_int_distribution.html `uniform_int_distribution`]
with a multiprecision generator such as [@http://www.boost.org/doc/html/boost/random/independent_bits_engine.html `independent_bits_engine`].
Or to use [@http://www.boost.org/doc/html/boost/random/uniform_smallint.html `uniform_smallint`] or
[@http://www.boost.org/doc/html/boost/random/random_number_generator.html `random_number_generator`] with multiprecision types.
floating-point values in \[0,1) are most easily generated using [@http://www.boost.org/doc/html/boost/random/generate_canonical.html `generate_canonical`],
note that `generate_canonical` will call the generator multiple times to produce the requested number of bits, for example we can use
it with a regular generator like so:
[random_eg3]
[random_eg3_out]
Note however, the distributions do not invoke the generator multiple times to fill up the mantissa of a multiprecision floating-point type
with random bits. For these therefore, we should probably use a multiprecision generator (ie `independent_bits_engine`) in combination
with the distribution:
[random_eg4]
[random_eg4_out]
And finally, it is possible to use the floating-point generators [@http://www.boost.org/doc/html/boost/random/lagged_fibonacci_01_engine.html `lagged_fibonacci_01_engine`]
and [@http://www.boost.org/doc/html/boost/random/subtract_with_idp144360752.html `subtract_with_carry_01_engine`] directly with multiprecision floating-point types.
It's worth noting however, that there is a distinct lack of literature on generating high bit-count random numbers, and therefore a lack of "known good" parameters to
use with these generators in this situation. For this reason, these should probably be used for research purposes only:
[random_eg5]
[endsect] [/section:random Generating Random Numbers]
[section:primetest Primality Testing]
The library implements a Miller-Rabin test for primality:
#include
template
bool miller_rabin_test(const number& n, unsigned trials, Engine& gen);
template
bool miller_rabin_test(const number& n, unsigned trials);
These functions perform a Miller-Rabin test for primality, if the result is `false` then /n/ is definitely composite,
while if the result is true then n is probably prime. The probability to declare a composite n as probable prime is
at most 0.25[super trials]. Note that this does not allow a statement about the probability of n being actually
prime (for that, the prior probability would have to be known). The algorithm used performs some
trial divisions to exclude small prime factors, does one Fermat test to exclude many more composites, and then
uses the Miller-Rabin algorithm straight out of
Knuth Vol 2, which recommends 25 trials for a pretty strong likelihood that /n/ is prime.
The third optional argument is for a Uniform Random Number Generator from Boost.Random. When not provided the `mt19937`
generator is used. Note that when producing random primes then you should probably use a different random number generator
to produce candidate prime numbers for testing, than is used internally by `miller_rabin_test` for determining
whether the value is prime. It also helps of course to seed the generators with some source of randomness.
The following example searches for a prime `p` for which `(p-1)/2` is also probably prime:
[safe_prime]
[endsect] [/section:primetest Primality Testing]
[section:lits Literal Types and `constexpr` Support]
There are two kinds of `constexpr` support in this library:
* The more basic version requires only C++11 and allow the construction of some number types as literals.
* The more advanced support permits constexpr arithmetic and requires at least C++14
constexpr support, and for many operations C++2a support
[h4 Declaring numeric literals]
There are two backend types which are literals:
* __float128__ (which requires GCC), and
* Instantiations of `cpp_int_backend` where the Allocator parameter is type `void`.
In addition, prior to C++14 the Checked parameter must be `boost::multiprecision::unchecked`.
For example:
using namespace boost::multiprecision;
constexpr float128 f = 0.1Q // OK, float128's are always literals in C++11
constexpr int128_t i = 0; // OK, fixed precision int128_t has no allocator.
constexpr uint1024_t j = 0xFFFFFFFF00000000uLL; // OK, fixed precision uint1024_t has no allocator.
constexpr checked_uint128_t k = 1; // OK from C++14 and later, not supported for C++11.
constexpr checked_uint128_t k = -1; // Error, as this would normally lead to a runtime failure (exception).
constexpr cpp_int l = 2; // Error, type is not a literal as it performs memory management.
There is also support for user defined-literals with __cpp_int - these are limited to unchecked, fixed precision `cpp_int`'s
which are specified in hexadecimal notation. The suffixes supported are:
[table
[[Suffix][Meaning]]
[[_cppi][Specifies a value of type: `number >`, where N is chosen
to contain just enough digits to hold the number specified.]]
[[_cppui][Specifies a value of type: `number >`, where N is chosen
to contain just enough digits to hold the number specified.]]
[[_cppi['N]][Specifies a value of type `number >`.]]
[[_cppui['N]][Specifies a value of type `number >`.]]
]
In each case, use of these suffixes with hexadecimal values produces a `constexpr` result.
Examples:
// Any use of user defined literals requires that we import the literal-operators into current scope first:
using namespace boost::multiprecision::literals;
//
// To keep things simple in the example, we'll make our types used visible to this scope as well:
using namespace boost::multiprecision;
//
// The value zero as a number >:
constexpr auto a = 0x0_cppi;
// The type of each constant has 4 bits per hexadecimal digit,
// so this is of type uint256_t (ie number >):
constexpr auto b = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF_cppui;
//
// Smaller values can be assigned to larger values:
int256_t c = 0x1234_cppi; // OK
//
// However, this only works in constexpr contexts from C++14 onwards:
constexpr int256_t d = 0x1_cppi; // Compiler error in C++11, requires C++14
//
// Constants can be padded out with leading zeros to generate wider types:
constexpr uint256_t e = 0x0000000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFF_cppui; // OK
//
// However, specific-width types are best produced with specific-width suffixes,
// ones supported by default are `_cpp[u]i128`, `_cpp[u]i256`, `_cpp[u]i512`, `_cpp[u]i1024`.
//
constexpr int128_t f = 0x1234_cppi128; // OK, always produces an int128_t as the result.
constexpr uint1024_t g = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccc_cppui1024; // OK,
// always produces an uint1024_t as the result.
//
// If other specific-width types are required, then there is a macro for generating the operators for these.
// The macro can be used at namespace scope only:
//
BOOST_MP_DEFINE_SIZED_CPP_INT_LITERAL(2048);
//
// Now we can create 2048-bit literals as well:
constexpr auto h = 0xff_cppi2048; // h is of type number >
//
// Finally, negative values are handled via the unary minus operator:
//
constexpr int1024_t i = -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF_cppui1024;
//
// Which means this also works:
constexpr int1024_t j = -g; // OK: unary minus operator is constexpr.
[h4 constexpr arithmetic]
The front end of the library is all `constexpr` from C++14 and later. Currently there are only two
backend types that are `constexpr` aware: __float128 and __cpp_int. More backends will follow at a later date.
Provided the compiler is GCC, type __float128__ support `constexpr` operations on all arithmetic operations from C++14, comparisons,
`abs`, `fabs`, `fpclassify`, `isnan`, `isinf`, `isfinite` and `isnormal` are also fully supported, but the transcendental functions are not.
The __cpp_int types support constexpr arithmetic, provided it is a fixed precision type with no allocator. It may also
be a checked integer: in which case a compiler error will be generated on overflow or undefined behaviour. In addition
the free functions `abs`, `swap`, `multiply`, `add`, `subtract`, `divide_qr`, `integer_modulus`, `powm`, `lsb`, `msb`,
`bit_test`, `bit_set`, `bit_unset`, `bit_flip`, `sqrt`, `gcd`, `lcm` are all supported. Use of __cpp_int in this way
requires either a C++2a compiler (one which supports `std::is_constant_evaluated()` - currently only gcc-9 or clang-9 or later),
or GCC-6 or later in C++14 mode.
Compilers other than GCC and without `std::is_constant_evaluated()` will support a very limited set of operations:
expect to hit roadblocks rather easily.
See __compiler_support for __is_constant_evaluated;
For example given:
[constexpr_circle]
We can now calculate areas and circumferences, using all compile-time `constexpr` arithmetic:
[constexpr_circle_usage]
Note that these make use of the numeric constants from the __math_constants library, which also happen to be `constexpr`.
These usually have the full precision of the floating-point type, here 128-bit, about 36 decimal digits.
[h5:hermite_poly_coeffics Calculating Hermite Polynomial coefficients at compile time]
For a more interesting example, in [@../../example/constexpr_float_arithmetic_examples.cpp constexpr_float_arithmetic_examples.cpp]
we define a simple class for `constexpr` polynomial arithmetic:
template
struct const_polynomial;
Given this, we can use recurrence relations to calculate the coefficients for various orthogonal
polynomials - in the example we use the Hermite polynomials. Only the constructor does any work -
it uses the recurrence relations to calculate the coefficient array:
[hermite_example]
Now we just need to define ['H[sub 0]] and ['H[sub 1]] as termination conditions for the recurrence:
[hermite_example2]
We can now declare ['H[sub 9]] as a `constexpr` object, access the coefficients, and evaluate
at an abscissa value, all at compile-time using `constexpr` arithmetic:
[hermite_example3]
See [@../../example/constexpr_float_arithmetic_examples.cpp constexpr_float_arithmetic_examples.cpp] for working code.
Also since the coefficients to the Hermite polynomials are integers, we can also generate the Hermite
coefficients using (fixed precision) `cpp_int`s: see [@../../test/constexpr_test_cpp_int_6.cpp constexpr_test_cpp_int_6.cpp].
[h5:factorial_constexpr `constexpr` Factorials]
We can also generate integer factorials in [@../../test/constexpr_test_cpp_int_5.cpp constexpr_test_cpp_int_5.cpp] like so:
[factorial_decl]
and validate the result:
constexpr uint1024_t f1 = factorial(uint1024_t(31)); // Factorial 31!
static_assert(f1 == 0x1956ad0aae33a4560c5cd2c000000_cppi); // Expected result as an Boost.Multiprecision integer literal.
[h5:random_constexpr Random `constexpr` values]
Another example in [@../../test/constexpr_test_cpp_int_7.cpp constexpr_test_cpp_int_7.cpp] generates
a fresh multiprecision random number each time the file is compiled. It includes an C++ template implementation of the
[@https://en.wikipedia.org/wiki/KISS_(algorithm) KISS random number algorithm by George Marsaglia] for `cpp_int` integers.
[random_constexpr_cppint]
See also the __random section.
[endsect] [/section:lits Literal Types and `constexpr` Support]
[section:import_export Importing and Exporting Data to and from `cpp_int` and `cpp_bin_float`]
Any integer number type that uses `cpp_int_backend` as its implementation layer can import or export its bits via two non-member functions:
template
OutputIterator export_bits(
const number, ExpressionTemplates>& val,
OutputIterator out,
unsigned chunk_size,
bool msv_first = true);
template
number, ExpressionTemplates>&
import_bits(
number, ExpressionTemplates>& val,
Iterator i,
Iterator j,
unsigned chunk_size = 0,
bool msv_first = true);
These functions are designed for data-interchange with other storage formats, and since __cpp_bin_float uses __cpp_int internally,
by extension they can be used for floating-point numbers based on that backend as well (see example below).
Parameters and use are as follows:
template
OutputIterator export_bits(
const number, ExpressionTemplates>& val,
OutputIterator out,
unsigned chunk_size,
bool msv_first = true);
Exports the absolute value of `val` to OutputIterator `out`. The function will write `chunk_size` bits at a time
to the OutputIterator, and if `msv_first` is true, will write the most-significant block first. Byte and bit order
within each `chunk_size` block is always in the machines native format. Further, each block is stored in a
`boost::uintmax_t` when it's assigned to `*out`.
[note Unfortunately, the standard's OutputIterator concept provides no means of deducing the type to output since
`std::iterator_traits::value_type` is type `void`. This is why the bit count for each block
has to be specified manually. It may also result in compiler warnings about the value being narrowed.]
[tip If you're exporting to non-native byte layout, then use
[@http://www.boost.org/doc/libs/release/libs/endian/doc/index.html Boost.Endian]
to create a custom OutputIterator that reverses the byte order of each chunk prior to actually storing the result.]
template
number, ExpressionTemplates>&
import_bits(
number, ExpressionTemplates>& val,
ForwardIterator i,
ForwardIterator j,
unsigned chunk_size = 0,
bool msv_first = true);
Imports bits from the iterator range ['\[i,j)] and stores them in `val` to produce an unsigned result (if the result
is to be signed you will need to handle that separately). When `msv_first` is true, takes `*i` as the most significant
chunk. Assumes there are `chunk_size` bits in each value read from the iterator range, and that these are in machine native
bit/byte order. When `chunk_size` is zero, then assumes that each chunk contains
`std::numeric_limits::value_type>::digits`, note that this will give the wrong result
if dereferencing the iterators leads to a signed-integer type, [*and] the sign bit is significant (be particularly careful
if you expect type `char` to contain 8-bit values, as by default it will extract only 7-bits at a time if `char` is signed).
As with exporting, if the external data is to be in a non-native byte order (within each chunk), then you will need to create an iterator adaptor
that presents it in native order (see [@http://www.boost.org/doc/libs/release/libs/endian/doc/index.html Boost.Endian]).
[note
Note that this function is optimized for the case where the data can be `memcpy`ed from the source to the integer - in this case both
iterators much be pointers, and everything must be little-endian.]
[h4 Examples]
[IE1]
[IE2]
[endsect] [/section:import_export Importing and Exporting Data to and from `cpp_int` and `cpp_bin_float`]
[section:rounding Rounding Rules for Conversions]
As a general rule, all conversions between unrelated types are performed using basic arithmetic operations, therefore
conversions are either exact, or follow the same rounding rules as arithmetic for the type in question.
The following table summarises the situation for conversions from native types:
[table
[[Backend][Rounding Rules]]
[[__cpp_int][Conversions from integer types are exact if the target has sufficient precision, otherwise they
truncate to the first 2^MaxBits bits (modulo arithmetic). Conversions from floating-point types
are truncating to the nearest integer.]]
[[__gmp_int][Conversions are performed by the GMP library except for conversion from `long double` which is truncating.]]
[[__tom_int][Conversions from floating-point types are truncating, all others are performed by libtommath and are exact.]]
[[__gmp_float][Conversions are performed by the GMP library except for conversion from `long double` which should be exact
provided the target type has as much precision as a `long double`.]]
[[__mpfr_float_backend][All conversions are performed by the underlying MPFR library.]]
[[__cpp_dec_float][All conversions are performed using basic arithmetic operations and are truncating.]]
[[__gmp_rational][See __gmp_int]]
[[__cpp_rational][See __cpp_int]]
[[__tommath_rational][See __tom_int]]
]
[endsect] [/section:rounding Rounding Rules for Conversions]
[section:mixed Mixed Precision Arithmetic]
Mixed precision arithmetic is fully supported by the library.
There are two different forms:
* Where the operands are of different precision.
* Where the operands are of the same precision, but yield a higher precision result.
[h4 Mixing Operands of Differing Precision]
If the arguments to a binary operator are of different precision, then the operation is allowed
as long as there is an unambiguous implicit conversion from one argument type to the other.
In all cases the arithmetic is performed "as if" the lower precision type is promoted to the
higher precision type before applying the operator. However, particular backends may optimise
this and avoid actually creating a temporary if they are able to do so.
For example:
mpfr_float_50 a(2), b;
mpfr_float_100 c(3), d;
static_mpfr_float_50 e(5), f;
mpz_int i(20);
d = a * c; // OK, result of operand is an mpfr_float_100.
b = a * c; // Error, can't convert the result to an mpfr_float_50 as it will lose digits.
f = a * e; // Error, operator is ambiguous, result could be of either type.
f = e * i; // OK, unambiguous conversion from mpz_int to static_mpfr_float_50
[h4 Operands of the Same Precision]
Sometimes you want to apply an operator to two arguments of the same precision in
such a way as to obtain a result of higher precision. The most common situation
occurs with fixed precision integers, where you want to multiply two N-bit numbers
to obtain a 2N-bit result. This is supported in this library by the following
free functions:
template