View Source Rational (qrational v1.3.0)

Elixir library implementing rational numbers and math.

The library adds new type of rational/0 numbers and basic math operations for them. Rationals can also interact with integers and floats. Actually this library expands existing functions, so they can work with rationals too. Number operations available:

  • addition
  • subtraction
  • multiplication
  • division
  • power

some-examples

Some examples

iex> use Rational
Rational

iex> ~n(2/12)
1/6

iex> ~n(1/4) * ~n(2/3)
1/6

iex> ~n(1/6) + ~n(4/7)
31/42

iex> ~n(7/9) ** 2
49/81

iex> ~n(33/7) - 5
-2/7

Link to this section Summary

Functions

Compares two rationals.

Returns true if term is a rational, otherwise returns false.

Parses a string into a rational.

Handles the sigil ~n for rationals.

Link to this section Types

@type operator() :: :+ | :- | :* | :/ | :**
@type rational() :: %Rational{denom: number(), num: number()}

Link to this section Functions

@spec compare(rational(), rational()) :: :lt | :eq | :gt

Compares two rationals.

Returns :gt if first rational is greater than the second and :lt for vice versa. If the two rationals are equal :eq is returned.

Link to this macro

is_rational(term)

View Source (macro)

Returns true if term is a rational, otherwise returns false.

Allowed in guard tests.

@spec parse(String.t()) :: rational() | number() | :error

Parses a string into a rational.

If successful, returns either a rational/0 or number/0; otherwise returns :error.

Link to this function

sigil_n(string, modifiers)

View Source
@spec sigil_n(String.t(), list()) :: rational()

Handles the sigil ~n for rationals.

It returns a rational/0 or number/0.

examples

Examples

iex> ~n(1/4)
1.0/4.0

iex> ~n(-3.1/5)
-3.1/5.0