# Rational data type

Last updated

Some programming languages provide a built-in (primitive) rational data type to represent rational numbers like 1/3 and -11/17 without rounding, and to do arithmetic on them. Examples are the `ratio` type of Common Lisp, and analogous types provided by most languages for algebraic computation, such as Mathematica and Maple. Many languages that do not have a built-in rational type still provide it as a library-defined type.

## Representation

A variable or value of that type is usually represented as a fraction m/n where m and n are two integer numbers, either with a fixed or arbitrary precision. Depending on the language, the denominator n may be constrained to be non-zero, and the two numbers may be kept in reduced form (without any common divisors except 1).

Languages that support a rational data type usually provide special syntax for building such values, and also extend the basic arithmetic operations ('+', '', '×', '/', integer powers) and comparisons ('=', '<', '>', '≤') to act on them — either natively or through operator overloading facilities provided by the language. These operations may be translated by the compiler into a sequence of integer machine instructions, or into library calls. Support may also extend to other operations, such as formatting, rounding to an integer or floating point value, etc.. As in mathematics, those languages often interpret an integer value as equivalent to a rational value with a unit denominator.

## Language support

Built-in or core library:

• C++ has included support for compile-time rational arithmetic in the form of the contents of its standard library's `<ratio>` header since its 2011 revision.
• Clojure can perform arithmetic on rational numbers and offers a literal form to represent them.
• Go provides rational numbers in the standard library, in the `math/big` package.
• J provides rational numbers in the base language. For example, `1r3` is one-third. Rationals in J use arbitrary precision integers for both the numerator and denominator, allowing arbitrary precision non-integers. For instance, `12683021339465478347804472r7322545784478161858100577` represents the square root of three to 50 decimal digits. 
• Julia provides rational numbers with the rational operator, `//`. For example, `6//9==2//3&&typeof(-4//9)==Rational{Int64}`. 
• Haskell provides a `Rational` type, which is really an alias for `Ratio Integer` (`Ratio` being a polymorphic type implementing rational numbers for any `Integral` type of numerators and denominators). The fraction is constructed using the % operator. 
• OCaml's Num library implements arbitrary-precision rational numbers.
• Perl: `Math::BigRat` core module implements arbitrary-precision rational numbers. The `bigrat` pragma can be used to turn on transparent BigRat support.
• Raku: use by default `Rat`  type (rational numbers with limited-precision). `FatRat`  data type implements arbitrary-precision rational numbers.
• Python 2.6+: Python's standard library includes a `Fraction` class in the module `fractions`. 
• Ruby 2.1 or newer: native support using special syntax.
• Ruby pre 2.1: via standard library includes a `Rational` class in the module `rational`.
• Smalltalk represents rational numbers using a `Fraction` class in the form `p/q` where `p` and `q` are arbitrary size integers. Applying the arithmetic operations `*`, `+`, `-`, `/`, to fractions returns a reduced fraction.

With external libraries:

### Common Lisp

Common Lisp provides a numeric data type for arbitrarily sized rational numbers: RATIO. 

`1/3⇒1/3`

The type of a rational number is `RATIO`:

`(type-of1/3)⇒RATIO`

Dividing two integers may return a rational number and the multiplication of a rational number may return an integer number:

`(/68)⇒3/4(*3/416)⇒12`

The numerator and denominator may be obtained using the homonymous functions, that reduce a rational to canonical form and compute the numerator or denominator of that form respectively: 

`(numerator12/16)⇒3(denominator12/16)⇒4`

Computing with large integers returning a large rational number:

`(/(1-(expt2200))(1-(expt243)))⇒1606938044258990275541962092341162602522202993782792835301375/8796093022207`

### Clojure

`(print (+ 1/10 2/10))  ⇒ 3/10 `

### Julia

`julia>1//10+2//103//10`

### Haskell

In module Data.Ratio

`(1 % 10) + (2 % 10)  ⇒ 3 % 10 `

### Racket (PLT Scheme)

`>(+1/102/10)3/10`

### Raku

Raku provides `Rat` type by default.

`my\$v = 0.2; say"{\$v} is {\$v.^name} and has numerator {\$v.numerator} and denominator {\$v.denominator}"; # ⇒ 0.2 is Rat and has numerator 1 and denominator 5`
`say0.1 + 0.2# ⇒ 0.3`
`say (0.1 + 0.2 - 0.3).fmt("%.17f") # ⇒ 0.00000000000000000`
`say1 / (0.1 + 0.2 - 0.3) # ⇒ Attempt to divide by zero when coercing Rational to Str`

### Ruby

Using special syntax in 2.1 or newer:

`irb(main):001:0> puts1/10r+2/10r3/10=> nil`

## Related Research Articles

The decimal numeral system is the standard system for denoting integer and non-integer numbers. It is the extension to non-integer numbers of the Hindu–Arabic numeral system. The way of denoting numbers in the decimal system is often referred to as decimal notation.

In computer science, an integer is a datum of integral data type, a data type that represents some range of mathematical integers. Integral data types may be of different sizes and may or may not be allowed to contain negative values. Integers are commonly represented in a computer as a group of binary digits (bits). The size of the grouping varies so the set of integer sizes available varies between different types of computers. Computer hardware, including virtual machines, nearly always provide a way to represent a processor register or memory address as an integer.

An irreducible fraction is a fraction in which the numerator and denominator are integers that have no other common divisors than 1. In other words, a fraction ab is irreducible if and only if a and b are coprime, that is, if a and b have a greatest common divisor of 1. In higher mathematics, "irreducible fraction" may also refer to rational fractions such that the numerator and the denominator are coprime polynomials. Every positive rational number can be represented as an irreducible fraction in exactly one way. Division is one of the four basic operations of arithmetic, the ways that numbers are combined to make new numbers. The other operations are addition, subtraction, and multiplication. The division sign ÷, a symbol consisting of a short horizontal line with a dot above and another dot below, is often used to indicate mathematical division. This usage, though widespread in anglophone countries, is neither universal nor recommended: the ISO 80000-2 standard for mathematical notation recommends only the solidus / or fraction bar for division, or the colon for ratios; it says that this symbol "should not be used" for division.

Double-precision floating-point format is a computer number format, usually occupying 64 bits in computer memory; it represents a wide dynamic range of numeric values by using a floating radix point. Rounding means replacing a number with an approximate value that has a shorter, simpler, or more explicit representation. For example, replacing \$23.4476 with \$23.45, the fraction 312/937 with 1/3, or the expression 2 with 1.414. In mathematics, division by zero is division where the divisor (denominator) is zero. Such a division can be formally expressed as a/0 where a is the dividend (numerator). In ordinary arithmetic, the expression has no meaning, as there is no number which, when multiplied by 0, gives a, and so division by zero is undefined. Since any number multiplied by zero is zero, the expression 0/0 is also undefined; when it is the form of a limit, it is an indeterminate form. Historically, one of the earliest recorded references to the mathematical impossibility of assigning a value to a/0 is contained in George Berkeley's criticism of infinitesimal calculus in 1734 in The Analyst.

In mathematics, a quadratic irrational number is an irrational number that is the solution to some quadratic equation with rational coefficients which is irreducible over the rational numbers. Since fractions in the coefficients of a quadratic equation can be cleared by multiplying both sides by their common denominator, a quadratic irrational is an irrational root of some quadratic equation whose coefficients are integers. The quadratic irrational numbers, a subset of the complex numbers, are algebraic numbers of degree 2, and can therefore be expressed as In arithmetic, a quotient is a quantity produced by the division of two numbers. The quotient has widespread use throughout mathematics, and is commonly referred to as the integer part of a division, or as a fraction or a ratio. For example, when dividing 20 by 3, the quotient is 6 in the Euclidean division sense, and in the proper division sense. In the second sense, a quotient is simply the ratio of a dividend to its divisor. GNU Multiple Precision Arithmetic Library (GMP) is a free library for arbitrary-precision arithmetic, operating on signed integers, rational numbers, and floating-point numbers. There are no practical limits to the precision except the ones implied by the available memory (operands may be of up to 232−1 bits on 32-bit machines and 237 bits on 64-bit machines). GMP has a rich set of functions, and the functions have a regular interface. The basic interface is for C, but wrappers exist for other languages, including Ada, C++, C#, Julia, .NET, OCaml, Perl, PHP, Python, R, Ruby and the Wolfram Language. Prior to 2008, Kaffe, a Java virtual machine, used GMP to support Java built-in arbitrary precision arithmetic. Shortly after, GMP support was added to GNU Classpath.

In computer science, arbitrary-precision arithmetic, also called bignum arithmetic, multiple-precision arithmetic, or sometimes infinite-precision arithmetic, indicates that calculations are performed on numbers whose digits of precision are limited only by the available memory of the host system. This contrasts with the faster fixed-precision arithmetic found in most arithmetic logic unit (ALU) hardware, which typically offers between 8 and 64 bits of precision.

bc, for basic calculator, is "an arbitrary-precision calculator language" with syntax similar to the C programming language. bc is typically used as either a mathematical scripting language or as an interactive mathematical shell. A fraction represents a part of a whole or, more generally, any number of equal parts. When spoken in everyday English, a fraction describes how many parts of a certain size there are, for example, one-half, eight-fifths, three-quarters. A common, vulgar, or simple fraction consists of a numerator displayed above a line, and a non-zero denominator, displayed below that line. Numerators and denominators are also used in fractions that are not common, including compound fractions, complex fractions, and mixed numerals.

Quote notation is a representation of the rational numbers based on Kurt Hensel's p-adic numbers. In quote notation, arithmetic operations take particularly simple, consistent forms, producing exact answers with no roundoff error. Quote notation’s arithmetic algorithms work in a right-to-left direction; addition, subtraction, and multiplication algorithms are the same as for natural numbers, and division is easier than the usual division algorithm. The notation was invented by Eric Hehner of the University of Toronto and Nigel Horspool, then at McGill University, and published in the SIAM Journal on Computing, v.8, n.2, May 1979, pp. 124–134.

CLN is a free library for arbitrary precision arithmetic. It operates on signed integers, rational numbers, floating point numbers, complex numbers, modular numbers, and univariate polynomials. Its implementation programming language is C++. In mathematics, a rational number is a number such as −3/7 that can be expressed as the quotient or fraction p/q of two integers, a numerator p and a non-zero denominator q. Every integer is a rational number: for example, 5 = 5/1. The set of all rational numbers, often referred to as "the rationals", the field of rationals or the field of rational numbers is usually denoted by a boldface Q ; it was thus denoted in 1895 by Giuseppe Peano after quoziente, Italian for "quotient".

Some programming languages provide a complex data type for complex number storage and arithmetic as a built-in (primitive) data type.

Some programming languages provide a built-in (primitive) or library decimal data type to represent non-repeating decimal fractions like 0.3 and -1.17 without rounding, and to do arithmetic on them. Examples are the `decimal.Decimal` type of Python, and analogous types provided by other languages. OpenLisp is a programming language in the Lisp family developed by Christian Jullien from Eligis. It conforms to the international standard for ISLISP published jointly by the International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC), ISO/IEC 13816:1997(E), revised to ISO/IEC 13816:2007(E).