### 21 releases (10 stable)

1.3.0 | Jan 26, 2019 |
---|---|

1.2.2 | Oct 18, 2018 |

1.2.0 | Jun 30, 2018 |

1.0.1 | Mar 10, 2018 |

0.5.0 | Jun 27, 2017 |

#**5** in Math

**377** downloads per month

Used in **11** crates

**LGPL-3.0+**

1.5MB

**24K**
SLoC

# Arbitrary-precision numbers

Rug provides integers and floating-point numbers with arbitrary precision and correct rounding:

is a bignum integer with arbitrary precision,`Integer`

is a bignum rational number with arbitrary precision,`Rational`

is a multi-precision floating-point number with correct rounding, and`Float`

is a multi-precision complex number with correct rounding.`Complex`

Rug is a high-level interface to the following GNU libraries:

- GMP for integers and rational numbers,
- MPFR for floating-point numbers, and
- MPC for complex numbers.

Rug is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. See the full text of the GNU LGPL and GNU GPL for details.

## What’s new

### Version 1.3.0 news (2019-01-26)

- The new method

was added.`SmallRational`assign_canonical`::`

### Version 1.2.3 news (2019-01-21)

- Fixed bug in

. (Thanks: Eric Scrivner)`Integer`assign_digits`::`

### Other releases

Details on other releases can be found in *RELEASES.md*.

## Quick example

`use` `rug``::``{`Assign`,` Integer`}``;`
`let` `mut` int `=` `Integer``::`new`(``)``;`
`assert_eq!``(`int`,` `0``)``;`
int`.``assign``(``14``)``;`
`assert_eq!``(`int`,` `14``)``;`
`let` decimal `=` `"`98_765_432_109_876_543_210`"``;`
int`.``assign``(``Integer``::`parse`(`decimal`)``.``unwrap``(``)``)``;`
`assert!``(`int `>` `100_000_000``)``;`
`let` hex_160 `=` `"`ffff0000ffff0000ffff0000ffff0000ffff0000`"``;`
int`.``assign``(``Integer``::`parse_radix`(`hex_160`,` `16``)``.``unwrap``(``)``)``;`
`assert_eq!``(`int`.``significant_bits``(``)``,` `160``)``;`
int `=` `(`int `>``>` `128``)` `-` `1``;`
`assert_eq!``(`int`,` `0xfffe_ffff_``u32``)``;`

creates a new`Integer`new`::``(``)`

intialized to zero.`Integer`- To assign values to Rug types, we use the

trait and its method`Assign`

. We do not use the assignment operator`assign`

as that would drop the left-hand-side operand and replace it with a right-hand-side operand of the same type, which is not what we want here.`=` - Arbitrary precision numbers can hold numbers that are too large to
fit in a primitive type. To assign such a number to the large
types, we use strings rather than primitives; in the example this
is done using

and`Integer`parse`::`

.`Integer`parse_radix`::` - We can compare Rug types to primitive types or to other Rug types
using the normal comparison operators, for example

.`int``>``100_000_000` - Most arithmetic operations are supported with Rug types and
primitive types on either side of the operator, for example

.`int``>``>``128`

## Using with primitive types

With Rust primitive types, arithmetic operators usually operate on two
values of the same type, for example

. Unlike primitive
types, conversion to and from Rug types can be expensive, so the
arithmetic operators are overloaded to work on many combinations of
Rug types and primitives. The following are provided:`12``i32` `+` `5``i32`

- Where they make sense, all arithmetic operators are overloaded to
work with Rug types and the primitives

,`i32`

,`u32`

and`f32`

.`f64` - Where they make sense, conversions using the

trait and assignments using the`From`

trait are supported for all the primitives in 1 above as well as the other primitives`Assign`

,`i8`

,`i16`

,`i64`

,`isize`

,`u8`

,`u16`

and`u64`

. This also applies to`usize`

and`i128`

if they are supported by the compiler.`u128` - Comparisons between Rug types and all the primitives listed in 1 and 2 above are supported.
- For

numbers, conversions and comparisons are also supported for tuples containing two integer primitives: the first is the numerator and the second is the denominator which must not be zero. The two primitives do not need to be of the same type.`Rational` - For

numbers, conversions and comparisons are also supported for tuples containing two primitives: the first is the real part and the second is the imaginary part. The two primitives do not need to be of the same type.`Complex`

## Operators

Operators are overloaded to work on Rug types alone or on a combination of Rug types and Rust primitives. When at least one operand is an owned value of a Rug type, the operation will consume that value and return a value of the Rug type. For example

`use` `rug``::`Integer`;`
`let` a `=` `Integer``::`from`(``10``)``;`
`let` b `=` `5` `-` a`;`
`assert_eq!``(`b`,` `5` `-` `10``)``;`

Here

is consumed by the subtraction, and `a`

is an owned
`b`

.`Integer`

If on the other hand there are no owned Rug types and there are references instead, the returned value is not the final value, but an incomplete-computation value. For example

`use` `rug``::`Integer`;`
`let` `(`a`,` b`)` `=` `(``Integer``::`from`(``10``)``,` `Integer``::`from`(``20``)``)``;`
`let` incomplete `=` `&`a `-` `&`b`;`
`//` This would fail to compile: assert_eq!(incomplete, -10);
`let` sub `=` `Integer``::`from`(`incomplete`)``;`
`assert_eq!``(`sub`,` `-``10``)``;`

Here

and `a`

are not consumed, and `b`

is not the final
value. It still needs to be converted or assigned into an `incomplete`

.
This is covered in more detail in the
`Integer`*Incomplete-computation values* section.

### Shifting operations

The left shift

and right shift `<``<`

operators support shifting by
negative values, for example `>``>`

is equivalent to `a << 5`

`a ``>``>` `-``5`

.The shifting operators are also supported for the

and
`Float`

number types, where they are equivalent to multiplication
or division by a power of two. Only the exponent of the value is
affected; the mantissa is unchanged.`Complex`

### Exponentiation

Exponentiation (raising to a power) does not have a dedicated operator
in Rust. In order to perform exponentiation of Rug types, the

trait has to be brought into scope, for example`Pow`

`use` `rug``::``ops``::`Pow`;`
`use` `rug``::`Integer`;`
`let` base `=` `Integer``::`from`(``10``)``;`
`let` power `=` base`.``pow``(``5``)``;`
`assert_eq!``(`power`,` `100_000``)``;`

### Compound assignments to right-hand-side operands

Traits are provided for compound assignment to right-hand-side
operands. This can be useful for non-commutative operations like
subtraction. The names of the traits and their methods are similar to
Rust compound assignment traits, with the suffix “

” replaced
with “`Assign`

”. For example the counterpart to `From`

is
`SubAssign`

:`SubFrom`

`use` `rug``::``ops``::`SubFrom`;`
`use` `rug``::`Integer`;`
`let` `mut` rhs `=` `Integer``::`from`(``10``)``;`
`//` set rhs = 100 − rhs
rhs`.``sub_from``(``100``)``;`
`assert_eq!``(`rhs`,` `90``)``;`

## Incomplete-computation values

There are two main reasons why operations like

do not
perform a complete computation and return a Rug type:`&`a `-` `&`b

- Sometimes we need to assign the result to an object that already exists. Since Rug types require memory allocations, this can help reduce the number of allocations. (While the allocations might not affect performance noticeably for computationally intensive functions, they can have a much more significant effect on faster functions like addition.)
- For the

and`Float`

number types, we need to know the precision when we create a value, and the operation itself does not convey information about what precision is desired for the result.`Complex`

There are two things that can be done with incomplete-computation values:

- Assign them to an existing object without unnecessary allocations.
This is usually achieved using the

trait or a similar method, for example`Assign`

and`int``.``assign``(`incomplete`)`

.`float``.``assign_round``(`incomplete`,``Round`Up`::``)` - Convert them to the final value using the

trait or a similar method, for example`From`

and`Integer`from`::``(`incomplete`)`

.`Float`with_val`::``(``53``,`incomplete`)`

Let us consider a couple of examples.

`use` `rug``::``{`Assign`,` Integer`}``;`
`let` `mut` buffer `=` `Integer``::`new`(``)``;`
`//` ... buffer can be used and reused ...
`let` `(`a`,` b`)` `=` `(``Integer``::`from`(``10``)``,` `Integer``::`from`(``20``)``)``;`
`let` incomplete `=` `&`a `-` `&`b`;`
buffer`.``assign``(`incomplete`)``;`
`assert_eq!``(`buffer`,` `-``10``)``;`

Here the assignment from

into `incomplete`

does not require
an allocation unless the result does not fit in the current capacity
of `buffer`

. If `buffer`

returned an `&`a `-` `&`b

instead, then an
allocation would take place even if it is not necessary.`Integer`

`use` `rug``::``float``::`Constant`;`
`use` `rug``::`Float`;`
`//` x has a precision of 10 bits
`let` x `=` `Float``::`with_val`(``10``,` `180``)``;`
`//` y has a precision of 50 bits
`let` y `=` `Float``::`with_val`(``50``,` `Constant``::`Pi`)``;`
`let` incomplete `=` `&`x `/` `&`y`;`
`//` z has a precision of 45 bits
`let` z `=` `Float``::`with_val`(``45``,` incomplete`)``;`
`assert!``(``57.``295` `<` z `&``&` z `<` `57.``296``)``;`

The precision to use for the result depends on the requirements of the
algorithm being implemented. Here

is created with a precision
of 45.`z`

Many operations can return incomplete-computation values:

- unary operators applied to references, for example

;`-``&`int - binary operators applied to two references, for example

;`&`int1`+``&`int2 - binary operators applied to a primitive and a reference, for
example

;`&`int`*``10` - methods that take a reference, for example

;`int``.``abs_ref``(``)` - methods that take two references, for example

;`int1``.``gcd_ref``(``&`int2`)` - string parsing, for example

;`Integer`parse`::``(``"`12`"``)` - and more.

These operations return objects that can be stored in temporary
variables like

in the last few examples. However, the
names of the types are not public, and consequently, the
incomplete-computation values cannot be for example stored in a
struct. If you need to store the value in a struct, convert it to its
final type and value.`incomplete`

## Using Rug

Rug is available on crates.io. To use Rug in your crate,
add it as a dependency inside *Cargo.toml*:

`[``dependencies``]`
`rug ``=` `"`1.3`"`

If you are using the 2015 Rust edition, you also need to declare it by
adding this to your crate root (usually *lib.rs* or *main.rs*):

`extern` `crate` rug`;`

Rug requires rustc version 1.18.0 or later.

Rug also depends on the GMP, MPFR and MPC libraries through the low-level FFI bindings in the gmp-mpfr-sys crate, which needs some setup to build; the gmp-mpfr-sys documentation has some details on usage under GNU/Linux, macOS and Windows.

## Optional features

The Rug crate has six optional features:

, enabled by default. Required for the`integer`

type and its supporting features.`Integer`

, enabled by default. Required for the`rational`

number type and its supporting features. This feature requires the`Rational`

feature.`integer`

, enabled by default. Required for the`float`

type and its supporting features.`Float`

, enabled by default. Required for the`complex`

number type and its supporting features. This feature requires the`Complex`

feature.`float`

, enabled by default. Required for the`rand`

type and its supporting features. This feature requires the`RandState`

feature.`integer`

, disabled by default. This provides serialization support for the`serde`

,`Integer`

,`Rational`

and`Float`

number types, providing that they are enabled. This feature requires the serde crate.`Complex`

The first five optional features are enabled by default; to use
features selectively, you can add the dependency like this to
*Cargo.toml*:

`[``dependencies.rug``]`
`version ``=` `"`1.3`"`
`default-features ``=` `false`
`features ``=` `[``"`integer`"`, `"`float`"`, `"`rand`"``]`

Here only the

, `integer`

and `float`

features are enabled. If
none of the features are selected, the gmp-mpfr-sys crate
is not required and thus not enabled. In that case, only the
`rand`

trait and the traits that are in the `Assign`

module are
provided by the crate.`ops`

#### Dependencies

~3.5MB

~87K SLoC