Карта сайта Kansoftware
НОВОСТИУСЛУГИРЕШЕНИЯКОНТАКТЫ
Разработка программного обеспечения

number

Boost , Chapter 1. Boost.Multiprecision , Reference

Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

PrevUpHomeNext
Synopsis
namespace boost{ namespace multiprecision{
enum expression_template_option { et_on = 1, et_off = 0 };
template <class Backend> struct expression_template_default
{ static const expression_template_option value = et_on; };
template <class Backend, expression_template_option ExpressionTemplates = expression_template_default<Backend>::value>
class number
{
   number();
   number(see-below);
   number& operator=(see-below);
   number& assign(see-below);
   // Member operators
   number& operator+=(const see-below&);
   number& operator-=(const see-below&);
   number& operator*=(const see-below&);
   number& operator/=(const see-below&);
   number& operator++();
   number& operator--();
   number  operator++(int);
   number  operator--(int);
   number& operator%=(const see-below&);
   number& operator&=(const see-below&);
   number& operator|=(const see-below&);
   number& operator^=(const see-below&);
   number& operator<<=(const integer-type&);
   number& operator>>=(const integer-type&);
   // Use in Boolean context:
   operator convertible-to-bool-type()const;
   // swap:
   void swap(number& other);
   // Sign:
   bool is_zero()const;
   int sign()const;
   // string conversion:
   std::string str()const;
   // Generic conversion mechanism
   template <class T>
   T convert_to()const;
   template <class T>
   explicit operator T ()const;
   // precision control:
   static unsigned default_precision();
   static void default_precision(unsigned digits10);
   unsigned precision()const;
   void precision(unsigned digits10);
   // Comparison:
   int compare(const number<Backend>& o)const;
   template <class V>
   typename enable_if<is_convertible<V, number<Backend, ExpressionTemplates> >, int>::type
      compare(const V& o)const;
   // Access to the underlying implementation:
   Backend& backend();
   const Backend& backend()const;
};
// Non member operators:
unmentionable-expression-template-type operator+(const see-below&);
unmentionable-expression-template-type operator-(const see-below&);
unmentionable-expression-template-type operator+(const see-below&, const see-below&);
unmentionable-expression-template-type operator-(const see-below&, const see-below&);
unmentionable-expression-template-type operator*(const see-below&, const see-below&);
unmentionable-expression-template-type operator/(const see-below&, const see-below&);
// Integer only operations:
unmentionable-expression-template-type operator%(const see-below&, const see-below&);
unmentionable-expression-template-type operator&(const see-below&, const see-below&);
unmentionable-expression-template-type operator|(const see-below&, const see-below&);
unmentionable-expression-template-type operator^(const see-below&, const see-below&);
unmentionable-expression-template-type operator<<(const see-below&, const integer-type&);
unmentionable-expression-template-type operator>>(const see-below&, const integer-type&);
// Comparison operators:
bool operator==(const see-below&, const see-below&);
bool operator!=(const see-below&, const see-below&);
bool operator< (const see-below&, const see-below&);
bool operator> (const see-below&, const see-below&);
bool operator<=(const see-below&, const see-below&);
bool operator>=(const see-below&, const see-below&);
// Swap:
template <class Backend, expression_template_option ExpressionTemplates>
void swap(number<Backend, ExpressionTemplates>& a, number<Backend, ExpressionTemplates>& b);
// iostream support:
template <class Backend, expression_template_option ExpressionTemplates>
std::ostream& operator << (std::ostream& os, const number<Backend, ExpressionTemplates>& r);
std::ostream& operator << (std::ostream& os, const unmentionable-expression-template-type& r);
template <class Backend, expression_template_option ExpressionTemplates>
std::istream& operator >> (std::istream& is, number<Backend, ExpressionTemplates>& r);
// Arithmetic with a higher precision result:
template <class ResultType, class Source1 class Source2>
ResultType& add(ResultType& result, const Source1& a, const Source2& b);
template <class ResultType, class Source1 class Source2>
ResultType& subtract(ResultType& result, const Source1& a, const Source2& b);
template <class ResultType, class Source1 class Source2>
ResultType& multiply(ResultType& result, const Source1& a, const Source2& b);
// min and max overloads:
number                                    min    (const number-or-expression-template-type&, const number-or-expression-template-type&);
number                                    max    (const number-or-expression-template-type&, const number-or-expression-template-type&);
// C90 Non-member function standard library support:
unmentionable-expression-template-type    abs    (const number-or-expression-template-type&);
unmentionable-expression-template-type    acos   (const number-or-expression-template-type&);
unmentionable-expression-template-type    asin   (const number-or-expression-template-type&);
unmentionable-expression-template-type    atan   (const number-or-expression-template-type&);
unmentionable-expression-template-type    atan2  (const number-or-expression-template-type&, const number-or-expression-template-type&);
unmentionable-expression-template-type    ceil   (const number-or-expression-template-type&);
unmentionable-expression-template-type    cos    (const number-or-expression-template-type&);
unmentionable-expression-template-type    cosh   (const number-or-expression-template-type&);
unmentionable-expression-template-type    exp    (const number-or-expression-template-type&);
unmentionable-expression-template-type    fabs   (const number-or-expression-template-type&);
unmentionable-expression-template-type    floor  (const number-or-expression-template-type&);
unmentionable-expression-template-type    fmod   (const number-or-expression-template-type&, const number-or-expression-template-type&);
number                                    frexp  (const number-or-expression-template-type&, integer-type*);
unmentionable-expression-template-type    ldexp  (const number-or-expression-template-type&, integer-type);
unmentionable-expression-template-type    log    (const number-or-expression-template-type&);
unmentionable-expression-template-type    log10  (const number-or-expression-template-type&);
number                                    modf   (const number-or-expression-template-type&, number*);
unmentionable-expression-template-type    pow    (const number-or-expression-template-type&, const number-or-expression-template-type&);
unmentionable-expression-template-type    sin    (const number-or-expression-template-type&);
unmentionable-expression-template-type    sinh   (const number-or-expression-template-type&);
unmentionable-expression-template-type    sqrt   (const number-or-expression-template-type&);
unmentionable-expression-template-type    tan    (const number-or-expression-template-type&);
unmentionable-expression-template-type    tanh   (const number-or-expression-template-type&);
// C99 Non-member function standard library support:
number                                    copysign  (const number-or-expression-template-type&, const number-or-expression-template-type&);
int                                              fpclassify(const number-or-expression-template-type&);
bool                                             isinf     (const number-or-expression-template-type&);
bool                                             isnan     (const number-or-expression-template-type&);
bool                                             isnormal  (const number-or-expression-template-type&);
integer-type                              ilogb     (const number-or-expression-template-type&);
unmentionable-expression-template-type    llround   (const number-or-expression-template-type&);
unmentionable-expression-template-type    logb      (const number-or-expression-template-type&);
unmentionable-expression-template-type    lround    (const number-or-expression-template-type&);
unmentionable-expression-template-type    round     (const number-or-expression-template-type&);
unmentionable-expression-template-type    scalbn    (const number-or-expression-template-type&, integer-type);
int                                              signbit   (const number-or-expression-template-type&);
unmentionable-expression-template-type    trunc     (const number-or-expression-template-type&);
// Misc other common C library functions:
number                                    changesign(const number-or-expression-template-type&);
unmentionable-expression-template-type    itrunc    (const number-or-expression-template-type&);
unmentionable-expression-template-type    ltrunc    (const number-or-expression-template-type&);
unmentionable-expression-template-type    lltrunc   (const number-or-expression-template-type&);
unmentionable-expression-template-type    iround    (const number-or-expression-template-type&);
int                                              sign      (const number-or-expression-template-type&);
// Traits support:
template <class T>
struct component_type;
template <class T>
struct number_category;
template <class T>
struct is_number;
template <class T>
struct is_number_expression;
// Integer specific functions:
unmentionable-expression-template-type    gcd(const number-or-expression-template-type&, const number-or-expression-template-type&);
unmentionable-expression-template-type    lcm(const number-or-expression-template-type&, const number-or-expression-template-type&);
unmentionable-expression-template-type    pow(const number-or-expression-template-type&, unsigned);
unmentionable-expression-template-type    powm(const number-or-expression-template-type& b, const number-or-expression-template-type& p, const number-or-expression-template-type& m);
unmentionable-expression-template-type    sqrt(const number-or-expression-template-type&);
template <class Backend, expression_template_option ExpressionTemplates>
number<Backend, EXpressionTemplates>      sqrt(const number-or-expression-template-type&, number<Backend, EXpressionTemplates>&);
template <class Backend, expression_template_option ExpressionTemplates>
void divide_qr(const number-or-expression-template-type& x, const number-or-expression-template-type& y,
               number<Backend, ExpressionTemplates>& q, number<Backend, ExpressionTemplates>& r);
template <class Integer>
Integer integer_modulus(const number-or-expression-template-type& x, Integer val);
unsigned lsb(const number-or-expression-template-type& x);
unsigned msb(const number-or-expression-template-type& x);
template <class Backend, class ExpressionTemplates>
bool bit_test(const number<Backend, ExpressionTemplates>& val, unsigned index);
template <class Backend, class ExpressionTemplates>
number<Backend, ExpressionTemplates>& bit_set(number<Backend, ExpressionTemplates>& val, unsigned index);
template <class Backend, class ExpressionTemplates>
number<Backend, ExpressionTemplates>& bit_unset(number<Backend, ExpressionTemplates>& val, unsigned index);
template <class Backend, class ExpressionTemplates>
number<Backend, ExpressionTemplates>& bit_flip(number<Backend, ExpressionTemplates>& val, unsigned index);
template <class Engine>
bool miller_rabin_test(const number-or-expression-template-type& n, unsigned trials, Engine& gen);
bool miller_rabin_test(const number-or-expression-template-type& n, unsigned trials);
// Rational number support:
typename component_type<number-or-expression-template-type>::type numerator  (const number-or-expression-template-type&);
typename component_type<number-or-expression-template-type>::type denominator(const number-or-expression-template-type&);
}} // namespaces
namespace boost{ namespace math{
// Boost.Math interoperability functions:
int                                              fpclassify     (const number-or-expression-template-type&, int);
bool                                             isfinite       (const number-or-expression-template-type&, int);
bool                                             isnan          (const number-or-expression-template-type&, int);
bool                                             isinf          (const number-or-expression-template-type&, int);
bool                                             isnormal       (const number-or-expression-template-type&, int);
}} // namespaces
// numeric_limits support:
namespace std{
template <class Backend, expression_template_option ExpressionTemplates>
struct numeric_limits<boost::multiprecision<Backend, ExpressionTemplates> >
{
   /* Usual members here */
};
}
Description
enum expression_template_option { et_on = 1, et_off = 0 };

Этот перечисленный тип используется для определения того, включены ли шаблоны выражения (et_on) или выключены (et_off).

template <class Backend> struct expression_template_default
{ static const expression_template_option value = et_on; };

Этот класс признаков определяет вариант шаблона выражения по умолчанию, который будет использоваться с определенным типом Backend. По умолчанию<et_on>.

template <class Backend, expression_template_option ExpressionTemplates = expression_template_default<Backend>::value>
class number;

Класс<number>имеет два шаблонных аргумента:

Backend

Фактический арифметический бэкэнд, который выполняет всю работу.

ExpressionTemplates

Булево значение: когда<et_on>, то шаблоны выражения включены, в противном случае, когда они установлены<et_off>, они отключены. По умолчанию этот параметр вычисляется через класс признаков<expression_template_default>, чей член<value>по умолчанию<et_on>, если класс признаков не является специализированным для конкретного бэкэнда.

number();
number(see-below);
number& operator=(see-below);
number& assign(see-below);

Тип<number>является конструируемым по умолчанию, и как копируемым, так и присваиваемым из:

  • Сама.
  • Шаблон выражения, являющийся результатом действия одного из арифметических операторов.
  • Любой встроенный арифметический тип до тех пор, пока результат не будет потерян (например, поплавок для целочисленного преобразования).
  • Любой тип, из которого Backend является неявно конструируемым или присваиваемым.
  • Ссылка на другое значение<number>. Move-семантика используется для строительства, если бэкэнд также поддерживает референтную конструкцию rvalue. В случае назначения семантика движения всегда поддерживается, когда аргумент является ссылкой на значение r, независимо от бэкэнда.
  • Любой тип в одном и том же семействе, при условии отсутствия потери точности. Например, от<int128_t>до<int256_t>или<cpp_dec_float_50>до<cpp_dec_float_100>.

Тип<number>явно конструируется из:

  • Любой тип, упомянутый выше.
  • <std::string>или любой другой тип, который может быть преобразован в<constchar*>.
  • Любой тип арифметики (включая те, которые приводят к потерям).
  • Любой тип в одном семействе, включая те, которые приводят к потере точности.
  • Любой тип, из которого Backend явно сконструирован.
  • Любая пара типов, для которых существует общая интерконверсия: то есть от целого к целому, от целого к рациональному, от целого к плавающему, от рационального к рациональному, от рационального к плавающему или от плавающего к плавающему.

Функция присваиваемого члена доступна для любого типа, для которого существует явно конвертирующий конструктор. Он предназначен для использования в тех случаях, когда временный результат явного назначения будет дорогостоящим, например:

mpfr_float_50    f50;
mpfr_float_100   f100;
f50 = static_cast<mpfr_float_50>(f100);  // explicit cast create a temporary
f50.assign(f100);                        // explicit call to assign create no temporary

Кроме того, если тип имеет несколько компонентов (например, рациональные или сложные типы чисел), то существует два конструктора аргументов:

number(arg1, arg2);

Там, где два арга должны быть либо арифметическими типами, либо типами, которые могут быть преобразованы в два компонента<this>.

number& operator+=(const see-below&);
number& operator-=(const see-below&);
number& operator*=(const see-below&);
number& operator/=(const see-below&);
number& operator++();
number& operator--();
number  operator++(int);
number  operator--(int);
// Integer only operations:
number& operator%=(const see-below&);
number& operator&=(const see-below&);
number& operator|=(const see-below&);
number& operator^=(const see-below&);
number& operator<<=(const integer-type&);
number& operator>>=(const integer-type&);

Все эти операторы принимают свои обычные арифметические значения.

Аргументы в пользу этих операторов таковы:

  • Еще один<number<Backend, ExpressionTemplates>>.
  • Выражение, полученное из<number<Backend>>.
  • Любой тип, неявно конвертируемый в<number<Backend,ExpressionTemplates>>, включая некоторый другой экземпляр класса<number>.

Для операций левого и правого сдвига аргумент должен быть встроенным целым типом с положительным значением (отрицательные значения приводят к бросанию<std::runtime_error>).

operator convertible-to-bool-type()const;

Возвращает неупорядоченный тип, который можно использовать в булевом контексте (это позволяет использовать<number>в любом булевом контексте - если утверждения, условные утверждения или в качестве аргумента для логического оператора - без конвертируемости типа<number>в тип<bool>.

Этот оператор также позволяет использовать<number>с любым из следующих операторов:<!>,<||>,<&&>и<?:>.

void swap(number& other);

<*this>и<other>.

bool is_zero()const;

Возврат<true>равен<*this>нулю, в противном случае<false>.

int sign()const;

Возвращает значение меньше нуля, если<*this>отрицательно, значение больше нуля, если<*this>положительно, и ноль, если<*this>ноль.

std::string str(unsigned precision, bool scientific = true)const;

Возвращает число, отформатированное как строка, с по меньшей мереточностьюцифр, и в научном формате, еслинаучноеверно.

template <class T>
T convert_to()const;
template <class T>
explicit operator T ()const;

Предоставляет общий механизм преобразования для преобразования<*this>в тип<T>. Тип<T>может быть любого арифметического типа. Другие типы могут также поддерживаться конкретными<Backend>типами.

static unsigned default_precision();
static void default_precision(unsigned digits10);
unsigned precision()const;
void precision(unsigned digits10);

Эти функции доступны только в том случае, если параметр шаблона Backend поддерживает изменения времени выполнения с точностью. Они получают и устанавливают по умолчанию точность и точность<*this>соответственно.

int compare(const number<Backend, ExpressionTemplates>& o)const;
template <class V>
typename enable_if<is_convertible<V, number<Backend, ExpressionTemplates> >, int>::type
   compare(const V& other)const;

Возвращение:

  • Значение меньше 0 для<*this<other>
  • Значение больше 0 для<*this>other>
  • Ноль для<*this ==other>

    <
    Backend&backend();
    constBackend&backend()const;
    
    >

Возвращает базовый бэкэнд, используемый<*this>.

Non-member operators
// Non member operators:
unmentionable-expression-template-type operator+(const see-below&);
unmentionable-expression-template-type operator-(const see-below&);
unmentionable-expression-template-type operator+(const see-below&, const see-below&);
unmentionable-expression-template-type operator-(const see-below&, const see-below&);
unmentionable-expression-template-type operator*(const see-below&, const see-below&);
unmentionable-expression-template-type operator/(const see-below&, const see-below&);
// Integer only operations:
unmentionable-expression-template-type operator%(const see-below&, const see-below&);
unmentionable-expression-template-type operator&(const see-below&, const see-below&);
unmentionable-expression-template-type operator|(const see-below&, const see-below&);
unmentionable-expression-template-type operator^(const see-below&, const see-below&);
unmentionable-expression-template-type operator<<(const see-below&, const integer-type&);
unmentionable-expression-template-type operator>>(const see-below&, const integer-type&);
// Comparison operators:
bool operator==(const see-below&, const see-below&);
bool operator!=(const see-below&, const see-below&);
bool operator< (const see-below&, const see-below&);
bool operator> (const see-below&, const see-below&);
bool operator<=(const see-below&, const see-below&);
bool operator>=(const see-below&, const see-below&);

Все эти операторы принимают свои обычные арифметические значения.

Аргументы в пользу этих функций должны содержать по меньшей мере одно из следующих:

  • А<number>.
  • Тип шаблона выражения, полученный из<number>.
  • Любой тип, для которого<number>имеет неявный конструктор — например, встроенный арифметический тип.

Тип возврата этих операторов:

  • неупорядоченный типшаблон выражения, когда<ExpressionTemplates><true>.
  • <number<Backend, et_off>>, когда<ExpressionTemplates><false>.
  • Тип<bool>, если оператор является оператором сравнения.

Наконец, обратите внимание, что второй аргумент для операций левого и правого сдвига должен быть встроенным целым типом и что аргумент должен быть положительным (отрицательные аргументы приводят к тому, что<std::runtime_error>бросается).

swap
template <class Backend, ExpressionTemplates>
void swap(number<Backend, ExpressionTemplates>& a, number<Backend, ExpressionTemplates>& b);

<a>и<b>.

Iostream Support
template <class Backend, expression_template_option ExpressionTemplates>
std::ostream& operator << (std::ostream& os, const number<Backend, ExpressionTemplates>& r);
template <class Unspecified...>
std::ostream& operator << (std::ostream& os, const unmentionable-expression-template& r);
template <class Backend, expression_template_option ExpressionTemplates>
inline std::istream& operator >> (std::istream& is, number<Backend, ExpressionTemplates>& r)

Эти операторы предоставляли отформатированные операции ввода-вывода на<number>типах и шаблоны выражения, полученные из них.

Это до бэкэнд-типа, чтобы фактически реализовать преобразование строк. Тем не менее, бэкэнды, предоставляемые этой библиотекой, поддерживают все флаги форматирования iostream, ширину поля и точные настройки.

Arithmetic with a higher precision result
template <class ResultType, class Source1 class Source2>
ResultType& add(ResultType& result, const Source1& a, const Source2& b);
template <class ResultType, class Source1 class Source2>
ResultType& subtract(ResultType& result, const Source1& a, const Source2& b);
template <class ResultType, class Source1 class Source2>
ResultType& multiply(ResultType& result, const Source1& a, const Source2& b);

Эти функции применяют названного оператора к аргументамaиbи сохраняют результат врезультате, возвращаярезультат. Во всех случаях они ведут себя «как если бы» аргументыaиbбыли сначала повышены до типа<ResultType>перед применением оператора, хотя отдельные бэкэнды вполне могут избежать этого шага путем оптимизации.

Тип<ResultType>должен быть экземпляром класса<number>, а типы<Source1>и<Source2>могут быть либо экземплярами класса<number>, либо нативными целыми типами. Последнее представляет собой оптимизацию, которая позволяет выполнять арифметику на нативных целочисленных типах, производя расширенный результат точности.

Non-member standard library function support
unmentionable-expression-template-type    abs    (const number-or-expression-template-type&);
unmentionable-expression-template-type    fabs   (const number-or-expression-template-type&);
unmentionable-expression-template-type    sqrt   (const number-or-expression-template-type&);
unmentionable-expression-template-type    floor  (const number-or-expression-template-type&);
unmentionable-expression-template-type    ceil   (const number-or-expression-template-type&);
unmentionable-expression-template-type    trunc  (const number-or-expression-template-type&);
unmentionable-expression-template-type    itrunc (const number-or-expression-template-type&);
unmentionable-expression-template-type    ltrunc (const number-or-expression-template-type&);
unmentionable-expression-template-type    lltrunc(const number-or-expression-template-type&);
unmentionable-expression-template-type    round  (const number-or-expression-template-type&);
unmentionable-expression-template-type    iround (const number-or-expression-template-type&);
unmentionable-expression-template-type    lround (const number-or-expression-template-type&);
unmentionable-expression-template-type    llround(const number-or-expression-template-type&);
unmentionable-expression-template-type    exp    (const number-or-expression-template-type&);
unmentionable-expression-template-type    log    (const number-or-expression-template-type&);
unmentionable-expression-template-type    log10    (const number-or-expression-template-type&);
unmentionable-expression-template-type    cos    (const number-or-expression-template-type&);
unmentionable-expression-template-type    sin    (const number-or-expression-template-type&);
unmentionable-expression-template-type    tan    (const number-or-expression-template-type&);
unmentionable-expression-template-type    acos   (const number-or-expression-template-type&);
unmentionable-expression-template-type    asin   (const number-or-expression-template-type&);
unmentionable-expression-template-type    atan   (const number-or-expression-template-type&);
unmentionable-expression-template-type    cosh   (const number-or-expression-template-type&);
unmentionable-expression-template-type    sinh   (const number-or-expression-template-type&);
unmentionable-expression-template-type    tanh   (const number-or-expression-template-type&);
unmentionable-expression-template-type    ldexp (const number-or-expression-template-type&, integer-type);
unmentionable-expression-template-type    frexp (const number-or-expression-template-type&, integer-type*);
unmentionable-expression-template-type    pow   (const number-or-expression-template-type&, const number-or-expression-template-type&);
unmentionable-expression-template-type    fmod  (const number-or-expression-template-type&, const number-or-expression-template-type&);
unmentionable-expression-template-type    atan2 (const number-or-expression-template-type&, const number-or-expression-template-type&);
unmentionable-expression-template-type    scalbn(const number-or-expression-template-type&, integer-type);
unmentionable-expression-template-type    logb  (const number-or-expression-template-type&);
integer-type                              ilogb (const number-or-expression-template-type&);

Все эти функции ведут себя точно так же, как и их коллеги из стандартной библиотеки C++11: их аргумент является либо экземпляром<number>, либо шаблоном выражения, полученным из него; если аргумент имеет тип<number<Backend,et_off>>, то это также тип возврата, в противном случае тип возврата является шаблоном выражения.

Аргументы целых типов для<ldexp>,<frexp>,<scalbn>и<ilogb>могут быть либо типом<int>, либо фактическим типом экспонента типа числа.

Эти функции обычно реализуются по типу Backend. Тем не менее, версии по умолчанию предоставляются для типов Backend, которые не имеют встроенной поддержки этих функций. Обратите внимание, однако, что эта поддержка по умолчанию требует, чтобы точность типа была постоянной времени компиляции - это означает, например, чтоGMPMPF Backend не будет работать с этими функциями, когда этот тип используется с переменной точностью.

Также обратите внимание, что за исключением<abs>, что эти функции могут использоваться только с типами бэкэндов с плавающей точкой (если позже в библиотеку добавляются любые другие типы, такие как фиксированная точность или сложные типы, то эти функции могут быть расширены для поддержки этих типов чисел).

Точность этих функций, как правило, определяется внутренней реализацией. Например, точность этих функций при использовании сmpfr_floatполностью определяетсяMPFR. Когда эти функции используют наши собственные реализации, точность трансцендентальных функций обычно составляет несколько эпсилон. Обратите внимание, однако, что тригонометрические функции несут обычную потерю точности при уменьшении аргументов на большие кратные числа π Также обратите внимание, что обаgmp_floatиcpp_dec_floatимеют ряд защитных цифр за пределами их заявленной точности, поэтому показатели ошибок, перечисленные для них, в некотором смысле искусственно низки.

В следующей таблице показаны показатели ошибок, которые мы наблюдаем для этих функций с различными типами бэкэнда, функции, не перечисленные здесь, являются точными (проверены на Win32 с VC++10, MPFR-3.0.0, MPIR-2.1.1):

Функция

mpfr_float_50

mpf_float_50

pp_dec_float_50

sqrt

1eps

0eps

0eps

exp

1eps

0eps

0eps

log

1eps

0eps

0eps

log10

1eps

0eps

0eps

Кос

700eps

0eps

0eps

Грех

1eps

0eps

0eps

Загар

0eps

0eps

0eps

acos

0eps

0eps

0eps

Асин

0eps

0eps

0eps

Атан

1eps

0eps

0eps

cosh

1045eps<number>

0eps

0eps

Синх

2eps

0eps

0eps

танх

1eps

0eps

0eps

Пау

0eps

4eps

3eps

атан2

1eps

0eps

0eps

<number>Вполне вероятно, что в этом виновата внутренняя ошибка входных значений в наших тестовых случаях.

Traits Class Support
template <class T>
struct component_type;

Если это тип с несколькими компонентами (например, рациональными или сложными типами), то эта черта имеет один элемент<type>, который является типом этих компонентов.

template <class T>
struct number_category;

Класс признаков, который наследует от<mpl::int_<N>>, где<N>является одним из перечисленных значений<number_kind_integer>,<number_kind_floating_point>,<number_kind_rational>,<number_kind_fixed_point>или<number_kind_unknown>. Этот класс признаков предназначен для любого типа, который имеет поддержку<std::numeric_limits>, а также для классов в этой библиотеке: это означает, что он может использоваться для общего кода, который должен работать со встроенными арифметическими типами, а также с многоточными.

template <class T>
struct is_number;

Класс признаков, который наследует от<mpl::true_>, если T является примером<number<>>, в противном случае от<mpl::false_>.

template <class T>
struct is_number_expression;

Класс признаков, который наследует от<mpl::true_>, если T является типом шаблона выражения, полученным от<number<>>, в противном случае от<mpl::false_>.

Integer functions

В дополнение к работе с типами из этой библиотеки, эти функции также перегружены для встроенных целых типов, если вы включаете<<boost/multiprecision/integer.hpp>>. Кроме того, при использовании с фиксированными типами точности (встроенными в целые числа или многоточные), функции будут продвигаться к более широкому типу внутри, когда этого требует алгоритм. Версии, перегруженные для встроенных целочисленных типов, возвращают этот целочисленный тип, а не шаблон выражения.

unmentionable-expression-template-type    gcd(const number-or-expression-template-type& a, const number-or-expression-template-type& b);

Возвращает наибольшее целое число<x>, которое делит как<a>, так и<b>.

unmentionable-expression-template-type    lcm(const number-or-expression-template-type& a, const number-or-expression-template-type& b);

Возвращает наименьшее целое число<x>, которое делится на<a>и<b>.

unmentionable-expression-template-type    pow(const number-or-expression-template-type& b, unsigned p);

Возвращаетbpв качестве шаблона выражения. Обратите внимание, что эта функция должна использоваться с особой осторожностью, поскольку в результате может вырасти настолько, что для вычисления потребуется «эффективно навсегда», или же просто запустить хост-машину из памяти. Это единственная функция в этой категории, которая не перегружена для встроенных целочисленных типов, кроме того, вероятно, не стоит использовать ее с фиксированной точностью<cpp_int>.

unmentionable-expression-template-type    powm(const number-or-expression-template-type& b, const number-or-expression-template-type& p, const number-or-expression-template-type& m);

Возвращаетbpmod mв качестве шаблона выражения. Внутренне продвигаются фиксированные типы точности для обеспечения точности.

unmentionable-expression-template-type    sqrt(const number-or-expression-template-type& a);

Возвращает наибольшее целое число<x>так, что<x* x< a>.

template <class Backend, expression_template_option ExpressionTemplates>
number<Backend, EXpressionTemplates>      sqrt(const number-or-expression-template-type& a, number<Backend, EXpressionTemplates>& r);

Возвращает наибольшее целое число<x>так, что<x* x< a>и устанавливает остаток<r>так, что<r =a-x* x>.

template <class Backend, expression_template_option ExpressionTemplates>
void divide_qr(const number-or-expression-template-type& x, const number-or-expression-template-type& y,
               number<Backend, ExpressionTemplates>& q, number<Backend, ExpressionTemplates>& r);

Разделяет x на y и возвращает как коэффициент, так и остаток. После призыва<q= x/y>и<r =x%y>

template <class Integer>
Integer integer_modulus(const number-or-expression-template-type& x, Integer val);

Возвращает абсолютное значение<x %val>.

unsigned lsb(const number-or-expression-template-type& x);

Возвращает (нулевой) индекс наименее значимого бита, который установлен на 1.

Бросает<std::range_error>, если аргумент<= 0.

unsigned msb(const number-or-expression-template-type& x);

Возвращает (нулевой) индекс самого значительного бита.

Бросает<std::range_error>, если аргумент<= 0.

template <class Backend, class ExpressionTemplates>
bool bit_test(const number<Backend, ExpressionTemplates>& val, unsigned index);

Возвращается<true>, если бит виндексеввалеустановлен.

template <class Backend, class ExpressionTemplates>
number<Backend, ExpressionTemplates>& bit_set(number<Backend, ExpressionTemplates>& val, unsigned index);

Устанавливает бит наиндексввали возвращаетвал.

template <class Backend, class ExpressionTemplates>
number<Backend, ExpressionTemplates>& bit_unset(number<Backend, ExpressionTemplates>& val, unsigned index);

Отключает бит виндексеввалеи возвращаетвале.

template <class Backend, class ExpressionTemplates>
number<Backend, ExpressionTemplates>& bit_flip(number<Backend, ExpressionTemplates>& val, unsigned index);

Переворачивает бит виндексввали возвращаетвал.

template <class Engine>
bool miller_rabin_test(const number-or-expression-template-type& n, unsigned trials, Engine& gen);
bool miller_rabin_test(const number-or-expression-template-type& n, unsigned trials);

Тесты, чтобы увидеть, является ли числоn, вероятно, простым - тест исключает подавляющее большинство составных чисел, исключая небольшие простые факторы и выполняя один тест Ферма. Затем выполняетиспытаниятесты Миллера-Рабина. Возвращается<false>, еслиnопределенно является составным, или<true>, еслиn, вероятно, является простым с вероятностью того, что он является составным менее 0,25^проб. Внутренне продвигаются фиксированные типы точности для обеспечения точности.

Rational Number Functions
typename component_type<number-or-expression-template-type>::type numerator  (const number-or-expression-template-type&);
typename component_type<number-or-expression-template-type>::type denominator(const number-or-expression-template-type&);

Эти функции возвращают числитель и знаменатель рационального числа соответственно.

Boost.Math Interoperability Support
namespace boost{ namespace math{
int  fpclassify     (const number-or-expression-template-type&, int);
bool isfinite       (const number-or-expression-template-type&, int);
bool isnan          (const number-or-expression-template-type&, int);
bool isinf          (const number-or-expression-template-type&, int);
bool isnormal       (const number-or-expression-template-type&, int);
}} // namespaces

Эти функции классификации с плавающей запятой ведут себя точно так же, как и их рост. Математические эквиваленты.

Другой рост. Математические функции и шаблоны также могут быть специализированными или перегруженными для обеспечения совместимости.

std::numeric_limits support
namespace std{
template <class Backend, ExpressionTemplates>
struct numeric_limits<boost::multiprecision<Backend, ExpressionTemplates> >
{
   /* Usual members here */
};
}

Шаблон класса<std::numeric_limits>предназначен для всех инстанциаций<number>, точность которых известна во время компиляции, а также для тех типов, точность которых не ограничена (хотя в этих случаях она гораздо менее полезна). Он не предназначен для типов, точность которых может изменяться во время компиляции (например,<mpf_float>).


PrevUpHomeNext

Статья number раздела Chapter 1. Boost.Multiprecision Reference может быть полезна для разработчиков на c++ и boost.




Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.



:: Главная :: Reference ::


реклама


©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007
Top.Mail.Ru

Время компиляции файла: 2024-08-30 11:47:00
2025-05-19 21:18:24/0.018014907836914/1