Some programming languages provide a built-in rational data type to represent rational numbers like 1/3 and -11/17 without rounding, and to do arithmetic on them. Examples are the 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 fractionm/n where m and n are two integer numbers, either with a fixed or arbitrary precision. Depending on the language, the denominatorn may be constrained to be non-zero, and the two numbers may be kept in reduced form. Languages that support a rational data type usually provide special syntax for building such values, and also extend the basic arithmetic operations 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.
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 .
J provides rational numbers in the base language. For example, is one-third. Rationals in J use arbitrary precision integers for both the numerator and denominator, allowing arbitrary precision non-integers. For instance, 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 Rational.
Haskell provides a type, which is really an alias for . The fraction is constructed using the % operator.
OCaml's Num library implements arbitrary-precision rational numbers.
Perl: core module implements arbitrary-precision rational numbers. The pragma can be used to turn on transparent BigRat support.
Raku: use by default type. data type implements arbitrary-precision rational numbers.
Python 2.6+: Python's standard library includes a class in the module.
Ruby 2.1 or newer: native support using special syntax.
Ruby pre 2.1: via standard library includes a class in the module.
Dividing two integers may return a rational number and the multiplication of a rational number may return an integer number:
⇒ 3/4
⇒ 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:
⇒ 3
⇒ 4
Computing with large integers returning a large rational number: