Ratio

hex.pm versionBuild Status

This library allows you to use Rational numbers in Elixir, to enable exact calculations with all numbers big and small.

Ratio follows the Numeric behaviour from Numbers, and can therefore be used in combination with any data type that uses Numbers (such as Tensor and ComplexNum).

Using Ratio

Ratio defines arithmetic and comparison operations to work with rational numbers.

Usually, you probably want to add the line import Ratio, only: [<|>: 2] to your code.

Shorthand operator

Rational numbers can be written using the operator <|> (as in: 1 <|> 2), which is also how Ratio structs are pretty-printed when inspecting. a <|> b is a shorthand for Ratio.new(a, b).

Basic functionality

Rational numbers can be manipulated using the functions in the Ratio module.

iex> Ratio.mult( 1 <|> 3, 1 <|> 2)
1 <|> 6
iex> Ratio.div(2 <|> 3, 8 <|> 5)
5 <|> 12
iex> Ratio.pow(Ratio.new(2), 4)
16 <|> 1

The ratio module also contains:

Inline Math Operators and Casting

Ratio interopts with the Numbers library: If you want to overload Elixir's builtin math operators, you can add use Numbers, overload_operators: true to your module.

This also allows you to pass in a rational number as one argument and an integer, float or Decimal (if you have installed the Decimal library), which are then cast to rational numbers whenever necessary.

Installation

The package can be installed from hex, by adding :ratio to your list of dependencies in mix.exs:

    def deps do
      [
        {:ratio, "~> 3.0"}
      ]
    end

Changelog

Difference with the 'rational' library

Observant readers might notice that there also is a 'rational' library in Hex.pm. The design idea between that library vs. this one is a bit different: Ratio hides the internal data representation as much as possible, and numbers are therefore created using Rational.<|>/2 or Ratio.new/2. This has as mayor advantage that the internal representation is always correct and simplified.

The Ratio library also (optionally) overrides the built-in math operations +, -, *, /, div, abs so they work with combinations of integers, floats and rationals.

Finally, Ratio follows the Numeric behaviour, which means that it can be used with any data types that follow Numbers.