Some
programming languages
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their syntax (form) and semantics (meaning), usually defined by a formal language. Languages usually provide features ...
provide a built-in (primitive) rational
data type
In computer science and computer programming, a data type (or simply type) is a collection or grouping of data values, usually specified by a set of possible values, a set of allowed operations on these values, and/or a representation of these ...
to represent
rational number
In mathematics, a rational number is a number that can be expressed as the quotient or fraction of two integers, a numerator and a non-zero denominator . For example, is a rational number, as is every integer (for example,
The set of all ...
s like 1/3 and −11/17 without
rounding
Rounding or rounding off is the process of adjusting a number to an approximate, more convenient value, often with a shorter or simpler representation. For example, replacing $ with $, the fraction 312/937 with 1/3, or the expression √2 with ...
, and to do arithmetic on them. Examples are the type of
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
, and analogous types provided by most languages for
algebraic computation, such as
Mathematica
Wolfram (previously known as Mathematica and Wolfram Mathematica) is a software system with built-in libraries for several areas of technical computing that allows machine learning, statistics, symbolic computation, data manipulation, network ...
and
Maple
''Acer'' is a genus of trees and shrubs commonly known as maples. The genus is placed in the soapberry family Sapindaceae.Stevens, P. F. (2001 onwards). Angiosperm Phylogeny Website. Version 9, June 2008 nd more or less continuously updated si ...
. Many languages that do not have a built-in rational type still provide it as a
library
A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
-defined type.
Representation
A variable or value of that type is usually represented as a
fraction
A fraction (from , "broken") 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, thre ...
''m''/''n'' where ''m'' and ''n'' are two
integer
An integer is the number zero (0), a positive natural number (1, 2, 3, ...), or the negation of a positive natural number (−1, −2, −3, ...). The negations or additive inverses of the positive natural numbers are referred to as negative in ...
numbers, either with a fixed or
arbitrary precision. Depending on the language, the
denominator
A fraction (from , "broken") 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, thre ...
''n''
may be constrained to be non-zero, and the two numbers may be kept in
reduced form (without any common
divisor
In mathematics, a divisor of an integer n, also called a factor of n, is an integer m that may be multiplied by some integer to produce n. In this case, one also says that n is a '' multiple'' of m. An integer n is divisible or evenly divisibl ...
s 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
In computer programming, operator overloading, sometimes termed ''operator ad hoc polymorphism'', is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading ...
facilities provided by the language. These operations may be translated by the
compiler
In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primaril ...
into a sequence of integer
machine instruction
In computer programming, machine code is computer code consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). For conventional binary computers, machine code is the binaryOn nonbi ...
s, or into
library
A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
calls. Support may also extend to other operations, such as formatting, rounding to an integer or
floating point
In computing, floating-point arithmetic (FP) is arithmetic on subsets of real numbers formed by a ''significand'' (a signed sequence of a fixed number of digits in some base) multiplied by an integer power of that base.
Numbers of this form ...
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'
headersince
its 2011 revision.
*
Clojure
Clojure (, like ''closure'') is a dynamic programming language, dynamic and functional programming, functional dialect (computing), dialect of the programming language Lisp (programming language), Lisp on the Java (software platform), Java platfo ...
can perform arithmetic on rational numbers and offers a literal form to represent them.
*
Go provides rational numbers in the standard library, in th
package
*
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(-4//9) Rational.
*
Haskell
Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
provides a type, which is really an alias for ( being a polymorphic type implementing rational numbers for any type of numerators and denominators). The fraction is constructed using the % operator.
*
OCaml
OCaml ( , formerly Objective Caml) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Comparison of multi-paradigm programming languages, multi-paradigm programming language which extends the ...
's Num library implements arbitrary-precision rational numbers.
*
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
: core module implements arbitrary-precision rational numbers. The pragma can be used to turn on transparent BigRat support.
*
Raku: use by default type (rational numbers with limited-precision). data type implements arbitrary-precision rational numbers.
*
Python: The standard library includes a class in the module .
*
Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
: native support using special syntax.
*
Smalltalk
Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
represents rational numbers using a class in the form where and are arbitrary size integers. Applying the arithmetic operations , , , , to fractions returns a
reduced fraction.
With external libraries:
* For
C &
C++ there are projects like the
GNU Multiple Precision Arithmetic Library
GNU Multiple Precision Arithmetic Library (GMP) is a free software, free library for arbitrary-precision arithmetic, operating on Sign (mathematics), signed integers, Rational data type, rational numbers, and Floating-point arithmetic, floating-p ...
.
* The
Apache Commons The Apache Commons is a project of the Apache Software Foundation, formerly under the Jakarta Project. The purpose of the Commons is to provide reusable, Open-source software, open source Java (software platform), Java software. The Commons is compo ...
Math library provides rational numbers for
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
with its class.
Common Lisp
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
provides a numeric data type for arbitrarily sized rational numbers: .
1/3
⇒ 1/3
The type of a rational number is :
(type-of 1/3)
⇒ RATIO
Dividing two integers may return a rational number and the multiplication of a rational number may return an integer number:
(/ 6 8)
⇒ 3/4
(* 3/4 16)
⇒ 12
The
numerator and
denominator
A fraction (from , "broken") 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, thre ...
may be obtained using the homonymous functions, that reduce a rational to canonical form and compute the numerator or denominator of that form respectively:
Function NUMERATOR, DENOMINATOR
at the Common Lisp HyperSpec
(numerator 12/16)
⇒ 3
(denominator 12/16)
⇒ 4
Computing with large integers returning a large rational number:
(/ (1- (expt 2 200)) (1- (expt 2 43)))
⇒ 1606938044258990275541962092341162602522202993782792835301375/8796093022207
Clojure
(print (+ 1/10 2/10))
⇒ 3/10
Julia
julia> 1//10 + 2//10
3//10
Haskell
In module Data.Ratio
(1 % 10) + (2 % 10)
⇒ 3 % 10
Racket (PLT Scheme)
> (+ 1/10 2/10)
3/10
Raku
Raku provides type by default.
my $v = 0.2;
say " is and has numerator and denominator ";
# ⇒ 0.2 is Rat and has numerator 1 and denominator 5
say 0.1 + 0.2
# ⇒ 0.3
say (0.1 + 0.2 - 0.3).fmt("%.17f")
# ⇒ 0.00000000000000000
say 1 / (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> puts 1/10r + 2/10r
3/10
=> nil
References
* Donald Knuth
Donald Ervin Knuth ( ; born January 10, 1938) is an American computer scientist and mathematician. He is a professor emeritus at Stanford University. He is the 1974 recipient of the ACM Turing Award, informally considered the Nobel Prize of comp ...
, ''The Art of Computer Programming
''The Art of Computer Programming'' (''TAOCP'') is a comprehensive multi-volume monograph written by the computer scientist Donald Knuth presenting programming algorithms and their analysis. it consists of published volumes 1, 2, 3, 4A, and 4 ...
'', vol. 2. Addison-Wesley.
{{Data types
Data types
Articles with example Julia code