HOME

TheInfoList



OR:

Some
programming languages A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
provide a built-in (primitive) rational
data type In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
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 (e.g. ). The set of all ra ...
s like 1/3 and -11/17 without
rounding Rounding means replacing a number with an approximate value that has a shorter, simpler, or more explicit representation. For example, replacing $ with $, the fraction 312/937 with 1/3, or the expression with . Rounding is often done to ob ...
, 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 ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fr ...
, and analogous types provided by most languages for algebraic computation, such as
Mathematica Wolfram Mathematica is a software system with built-in libraries for several areas of technical computing that allow machine learning, statistics, symbolic computation, data manipulation, network analysis, time series analysis, NLP, optimiza ...
and
Maple ''Acer'' () is a genus of trees and shrubs commonly known as maples. The genus is placed in the family Sapindaceae.Stevens, P. F. (2001 onwards). Angiosperm Phylogeny Website. Version 9, June 2008 nd more or less continuously updated since h ...
. Many languages that do not have a built-in rational type still provide it as a
library A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vi ...
-defined type.


Representation

A variable or value of that type is usually represented as a
fraction A fraction (from la, fractus, "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 ...
''m''/''n'' where ''m'' and ''n'' are two
integer An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign ( −1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the languag ...
numbers, either with a fixed or arbitrary precision. Depending on the language, the
denominator A fraction (from la, fractus, "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 ...
''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 divisible by ...
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 i ...
facilities provided by the language. These operations may be translated by the
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs tha ...
into a sequence of integer
machine instruction In computer programming, machine code is any low-level programming language, consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). Each instruction causes the CPU to perform a very ...
s, or into
library A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vi ...
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 that represents real numbers approximately, using an integer with a fixed precision, called the significand, scaled by an integer exponent of a fixed base. For example, 12.345 can ...
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++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
has included support for compile-time rational arithmetic in the form of the contents of its standard library'
header
since its 2011 revision. *
Clojure Clojure (, like ''closure'') is a dynamic and functional dialect of the Lisp programming language on the Java platform. Like other Lisp dialects, Clojure treats code as data and has a Lisp macro system. The current development process is comm ...
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 Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e.g ...
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 has pioneered a number of programming lan ...
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, multi-paradigm programming language Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. ...
's Num library implements arbitrary-precision rational numbers. *
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
: 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 2.6+: Python's standard library includes a class in the module . *
Ruby A 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 ...
2.1 or newer: native support using special syntax. * Ruby pre 2.1: via standard library includes a class in the module . *
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan ...
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 An irreducible fraction (or fraction in lowest terms, simplest form or reduced fraction) is a fraction in which the numerator and denominator are integers that have no other common divisors than 1 (and −1, when negative numbers are considered). ...
. With external libraries: * For C &
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
there are projects like the GNU Multiple Precision Arithmetic Library. * 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 Java software. The Commons is composed of three parts: proper, sandbox, and dorman ...
Math library provides rational numbers for
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
with its class.


Common Lisp

Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fr ...
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 A fraction (from la, fractus, "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 ...
and
denominator A fraction (from la, fractus, "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 ...
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, mathematician, and professor emeritus at Stanford University. He is the 1974 recipient of the ACM Turing Award, informally considered the Nobel Prize of computer sc ...
, ''
The Art of Computer Programming ''The Art of Computer Programming'' (''TAOCP'') is a comprehensive monograph written by the computer scientist Donald Knuth presenting programming algorithms and their analysis. Volumes 1–5 are intended to represent the central core of com ...
'', vol. 2. Addison-Wesley. {{Data types Data types Articles with example Julia code