Programming Search⌘K

Conceptadvanced

Rational numbers in code

Also called rational number type, rational data type, fraction type, ratio, Fraction, Rational, BigRational, exact fractions.

A rational type stores a fraction as two integers in lowest terms, so 1/3 and 1/10 are exact. The cost is that the two integers can grow large during a long calculation.

Applies to
core-languages

Idea

A binary floating-point number cannot hold 1/10 or 1/3 exactly. A rational type can. Wikipedia says such a type represents "rational numbers like 1/3 and −11/17 without rounding"1, and the value "is usually represented as a fraction m/n where m and n are two integer numbers, either with a fixed or arbitrary precision"1.

Most rational types keep the fraction in a normal form: the numerator and the denominator have no common factor, and the denominator is positive. Then each value has one representation, so equality is a compare of the two integers. Each operation computes the new numerator and denominator with integer arithmetic, then divides both by their greatest common divisor (GCD).

from math import gcd


def make(n, d):
    if d == 0:
        raise ZeroDivisionError("denominator is 0")
    if d < 0:
        n, d = -n, -d
    g = gcd(n, d)
    return n // g, d // g


def add(a, b):
    return make(a[0] * b[1] + b[0] * a[1], a[1] * b[1])


def mul(a, b):
    return make(a[0] * b[0], a[1] * b[1])


print("make(6, -8):", make(6, -8))
print("1/10 + 2/10:", add(make(1, 10), make(2, 10)))
print("0.1 + 0.2 == 0.3:", "yes" if 0.1 + 0.2 == 0.3 else "no")
same = add(make(1, 10), make(2, 10)) == make(3, 10)
print("1/10 + 2/10 == 3/10:", "yes" if same else "no")
print("3/4 * 16:", mul(make(3, 4), make(16, 1)))
h = make(0, 1)
for k in range(1, 31):
    h = add(h, make(1, k))
    if k in (10, 20, 30):
        print(f"1/1 + ... + 1/{k} = {h[0]}/{h[1]}")
Output
make(6, -8): (-3, 4)
1/10 + 2/10: (3, 10)
0.1 + 0.2 == 0.3: no
1/10 + 2/10 == 3/10: yes
3/4 * 16: (12, 1)
1/1 + ... + 1/10 = 7381/2520
1/1 + ... + 1/20 = 55835135/15519504
1/1 + ... + 1/30 = 9304682830147/2329089562800

The last three lines show the main cost. The sum of 30 small fractions has a denominator of 13 digits, and the parts get longer as the sum goes on.

How it works

Normal form. Common Lisp defines its ratio type in this form: "A ratio is a number representing the mathematical ratio of two non-zero integers, the numerator and denominator, whose greatest common divisor is one, and of which the denominator is positive and greater than one."2 So (/ 6 8) gives 3/4, and (* 3/4 16) gives the integer 121. Haskell's numerator and denominator give the parts "in reduced form: the numerator and denominator have no common factor and the denominator is positive"3. Python's Fraction(16, -10) gives Fraction(-8, 5)4, and the documentation says: "The math.gcd() function is now used to normalize the numerator and denominator."4

The width of the parts. If the numerator and the denominator are bignums, the rational type is exact for all four operations, except division by zero. If they are fixed-width integers, the parts can overflow. Haskell's Rational is "Arbitrary-precision rational numbers, represented as a ratio of two Integer values"3, but the general Ratio a type works with any integral type, and its instances "inherit the deficiencies from the type parameter's"3. The Rust crate num-rational has both kinds: BigRational is an "Alias for arbitrary precision rationals"5, and Rational64 is an "Alias for a Ratio of 64-bit-sized integers"5.

Conversion from a float. A float has an exact binary value, so a conversion to a rational type gives that exact value, not the decimal value in the source code. Python's documentation says that "Fraction(1.1) does not return Fraction(11, 10) as one might expect"4. It gives Fraction(2476979795053773, 2251799813685248)4. A string such as '1.1' gives 11/10. Go's Rat.SetFloat64 also "sets z to exactly f"6. To get a simple fraction back, Python has limit_denominator, which "Finds and returns the closest Fraction to self that has denominator at most max_denominator"4.

Conversion to text and floats. Go's FloatString gives a decimal string with a set number of digits, and "The last digit is rounded to nearest, with halves rounded away from zero."6 A conversion to a float rounds again.

In languages

LanguageVerdictNote
PythonStandard library
C++Library
JavaLibrary
CLibrary
C#Idiom
JavaScriptIdiom
TypeScriptIdiomTypeScript has no rational type, so a program keeps a pair of bigint values in lowest terms, as in JavaScript. No example file exists.
GoStandard library
RustLibrary
KotlinIdiomKotlin has no rational type, so a program keeps a pair of java.math.BigInteger values and uses gcd to reduce them. No example file exists because kotlinc is not installed.
SQLAbsentSQL has no rational type; NUMERIC and DECIMAL are decimal types with a declared precision. No example file exists.
BashAbsentBash arithmetic expansion has integers only, with no fraction type. No example file exists.
PowerShellIdiomPowerShell has no rational type, so a script keeps a pair of [bigint] values and reduces them with the .NET GreatestCommonDivisor method. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no arithmetic.
CSSDoes not applyCSS has no rational type.
Regular expressionsDoes not applyA pattern matches digits as text but does no arithmetic.
Language Verdict Rational type
Python stdlib fractions.Fraction
JavaScript idiom none; a pair of bigint values
TypeScript idiom as JavaScript
Java library none in the JDK; Apache Commons Math Fraction
Kotlin idiom none; a pair of BigInteger values
C# idiom none; a pair of BigInteger values
Go stdlib math/big Rat
Rust library the num-rational crate
C library GMP mpq_t
C++ library GMP mpq_class; std::ratio at compile time only
Bash absent integer arithmetic only
PowerShell idiom none; a pair of [bigint] values
SQL absent no rational type; NUMERIC is decimal
Regex n/a no arithmetic
HTML n/a no arithmetic
CSS n/a no rational type

Wikipedia lists the languages with a rational type in the language or the core library: C++ has had "compile-time rational arithmetic"1 in the <ratio> header since 2011, Go has rationals in math/big, Haskell has Rational, Python has Fraction, and Common Lisp, Clojure, Julia, Ruby, Raku and Smalltalk have rationals too1. For C and C++ there is GMP, and "The Apache Commons Math library provides rational numbers for Java with its Fraction class."1 GMP operates "on signed integers, rational numbers, and floating-point numbers"7, and its C++ class for rationals is mpq_class7.

PythonGitHub
from fractions import Fraction

print("Fraction(16, -10):", Fraction(16, -10))
s = Fraction(1, 10) + Fraction(2, 10)
print("1/10 + 2/10:", s, "equal to 3/10:", "yes" if s == Fraction(3, 10) else "no")
print("Fraction(1.1):", Fraction(1.1))
print("Fraction('1.1'):", Fraction("1.1"))
print("Fraction(1.1).limit_denominator():", Fraction(1.1).limit_denominator())
pi = Fraction("3.1415926535897932")
print("pi.limit_denominator(1000):", pi.limit_denominator(1000))
t = Fraction(1, 3) ** 40
print("digits of (1/3)**40 denominator:", len(str(t.denominator)))
print("float(Fraction(1, 3)):", float(Fraction(1, 3)))
try:
    Fraction(1, 0)
except ZeroDivisionError as e:
    print("Fraction(1, 0):", type(e).__name__)
Output
Fraction(16, -10): -8/5
1/10 + 2/10: 3/10 equal to 3/10: yes
Fraction(1.1): 2476979795053773/2251799813685248
Fraction('1.1'): 11/10
Fraction(1.1).limit_denominator(): 11/10
pi.limit_denominator(1000): 355/113
digits of (1/3)**40 denominator: 20
float(Fraction(1, 3)): 0.3333333333333333
Fraction(1, 0): ZeroDivisionError
  • Verdict: stdlib. fractions.Fraction keeps the value in lowest terms with a positive denominator, and its parts are int values, so they do not overflow.
  • Fraction(1.1) is the exact value of the float, and Fraction("1.1") is 11/10.
  • limit_denominator finds a near fraction with a small denominator.
#include <cstdint>
#include <iostream>
#include <numeric>
#include <ratio>
#include <stdexcept>

struct Ratio {
    std::int64_t n;
    std::int64_t d;
};

Ratio make(std::int64_t n, std::int64_t d) {
    if (d == 0) {
        throw std::domain_error("denominator is 0");
    }
    if (d < 0) {
        n = -n;
        d = -d;
    }
    std::int64_t g = std::gcd(n, d);
    return {n / g, d / g};
}

Ratio add(Ratio a, Ratio b) {
    return make(a.n * b.d + b.n * a.d, a.d * b.d);
}

int main() {
    using sum = std::ratio_add<std::ratio<1, 10>, std::ratio<2, 10>>;
    std::cout << "std::ratio 1/10 + 2/10: " << sum::num << '/' << sum::den << '\n';
    using r = std::ratio<6, -8>;
    std::cout << "std::ratio<6, -8>: " << r::num << '/' << r::den << '\n';
    static_assert(std::ratio_equal_v<sum, std::ratio<3, 10>>);

    Ratio s = add(make(1, 10), make(2, 10));
    std::cout << "runtime 1/10 + 2/10: " << s.n << '/' << s.d << '\n';
    try {
        make(1, 0);
    } catch (const std::domain_error &e) {
        std::cout << "make(1, 0): " << e.what() << '\n';
    }
}
Output
std::ratio 1/10 + 2/10: 3/10
std::ratio<6, -8>: -3/4
runtime 1/10 + 2/10: 3/10
make(1, 0): denominator is 0
  • Verdict: library. std::ratio computes with fractions at compile time only, and it keeps them in lowest terms with a positive denominator. For values at run time, GMP has the mpq_class class.
  • The Ratio struct here has std::int64_t parts, so its products can overflow without a check.
JavaGitHub
import java.math.BigInteger;

public class Main {
  record Ratio(BigInteger n, BigInteger d) {
    static Ratio of(long n, long d) {
      return make(BigInteger.valueOf(n), BigInteger.valueOf(d));
    }

    static Ratio make(BigInteger n, BigInteger d) {
      if (d.signum() == 0) {
        throw new ArithmeticException("denominator is 0");
      }
      if (d.signum() < 0) {
        n = n.negate();
        d = d.negate();
      }
      BigInteger g = n.gcd(d);
      return new Ratio(n.divide(g), d.divide(g));
    }

    Ratio add(Ratio o) {
      return make(n.multiply(o.d).add(o.n.multiply(d)), d.multiply(o.d));
    }

    @Override
    public String toString() {
      return n + "/" + d;
    }
  }

  public static void main(String[] args) {
    System.out.println("of(6, -8): " + Ratio.of(6, -8));
    Ratio s = Ratio.of(1, 10).add(Ratio.of(2, 10));
    System.out.println("1/10 + 2/10: " + s);
    System.out.println("equal to 3/10: " + (s.equals(Ratio.of(3, 10)) ? "yes" : "no"));
    System.out.println("0.1 + 0.2: " + (0.1 + 0.2));
    Ratio h = Ratio.of(0, 1);
    for (int k = 1; k <= 30; k++) {
      h = h.add(Ratio.of(1, k));
    }
    System.out.println("1/1 + ... + 1/30: " + h);
    try {
      Ratio.of(1, 0);
    } catch (ArithmeticException e) {
      System.out.println("of(1, 0): ArithmeticException");
    }
  }
}
Output
of(6, -8): -3/4
1/10 + 2/10: 3/10
equal to 3/10: yes
0.1 + 0.2: 0.30000000000000004
1/1 + ... + 1/30: 9304682830147/2329089562800
of(1, 0): ArithmeticException
  • Verdict: library. The JDK has no rational type, and Apache Commons Math has a Fraction class. The block uses a record of two BigInteger values instead, with BigInteger.gcd for the normal form.
  • A record gets equals from its fields, so two values in lowest terms compare correctly.
#include <stdio.h>

typedef struct {
    long long n;
    long long d;
} ratio;

static long long gcd(long long a, long long b) {
    while (b != 0) {
        long long t = a % b;
        a = b;
        b = t;
    }
    return a < 0 ? -a : a;
}

static int make(long long n, long long d, ratio *out) {
    if (d == 0) {
        return -1;
    }
    if (d < 0) {
        n = -n;
        d = -d;
    }
    long long g = gcd(n, d);
    out->n = n / g;
    out->d = d / g;
    return 0;
}

static int add(ratio a, ratio b, ratio *out) {
    long long x = 0;
    long long y = 0;
    long long n = 0;
    long long d = 0;
    if (__builtin_mul_overflow(a.n, b.d, &x) || __builtin_mul_overflow(b.n, a.d, &y) ||
        __builtin_add_overflow(x, y, &n) || __builtin_mul_overflow(a.d, b.d, &d)) {
        return -1;
    }
    return make(n, d, out);
}

int main(void) {
    ratio r = {0, 1};
    make(6, -8, &r);
    printf("make(6, -8): %lld/%lld\n", r.n, r.d);
    ratio a = {0, 1};
    ratio b = {0, 1};
    make(1, 10, &a);
    make(2, 10, &b);
    add(a, b, &r);
    printf("1/10 + 2/10: %lld/%lld\n", r.n, r.d);
    printf("0.1 + 0.2 == 0.3: %s\n", 0.1 + 0.2 == 0.3 ? "yes" : "no");
    printf("make(1, 0): %s\n", make(1, 0, &r) == 0 ? "ok" : "error");
    ratio h = {0, 1};
    for (long long k = 1; k <= 20; k++) {
        ratio t = {0, 1};
        make(1, k, &t);
        add(h, t, &h);
    }
    printf("1/1 + ... + 1/20: %lld/%lld\n", h.n, h.d);
    return 0;
}
Output
make(6, -8): -3/4
1/10 + 2/10: 3/10
0.1 + 0.2 == 0.3: no
make(1, 0): error
1/1 + ... + 1/20: 55835135/15519504
  • Verdict: library. C has no rational type, and GMP has the mpq_t type, with bignum parts.
  • The block uses long long parts and returns -1 on a zero denominator or an overflow, so the caller must check each result.
using System;
using System.Numerics;

static Ratio Make(BigInteger n, BigInteger d)
{
    if (d.IsZero)
    {
        throw new DivideByZeroException();
    }
    if (d.Sign < 0)
    {
        n = -n;
        d = -d;
    }
    BigInteger g = BigInteger.GreatestCommonDivisor(n, d);
    return new Ratio(n / g, d / g);
}

static Ratio Add(Ratio a, Ratio b) => Make(a.N * b.D + b.N * a.D, a.D * b.D);

Console.WriteLine($"Make(6, -8): {Make(6, -8)}");
Ratio s = Add(Make(1, 10), Make(2, 10));
Console.WriteLine($"1/10 + 2/10: {s}");
Console.WriteLine($"equal to 3/10: {(s == Make(3, 10) ? "yes" : "no")}");
Console.WriteLine($"0.1 + 0.2 == 0.3: {(0.1 + 0.2 == 0.3 ? "yes" : "no")}");
Ratio h = Make(0, 1);
for (int k = 1; k <= 20; k++)
{
    h = Add(h, Make(1, k));
}
Console.WriteLine($"1/1 + ... + 1/20: {h}");
try
{
    Make(1, 0);
}
catch (DivideByZeroException)
{
    Console.WriteLine("Make(1, 0): DivideByZeroException");
}

record struct Ratio(BigInteger N, BigInteger D)
{
    public override string ToString() => $"{N}/{D}";
}
Output
Make(6, -8): -3/4
1/10 + 2/10: 3/10
equal to 3/10: yes
0.1 + 0.2 == 0.3: no
1/1 + ... + 1/20: 55835135/15519504
Make(1, 0): DivideByZeroException
  • Verdict: idiom. .NET has no rational type, so the block keeps a record struct of two BigInteger values in lowest terms.
  • BigInteger.GreatestCommonDivisor gives the GCD, and the record struct gets == from its fields.
JavaScriptGitHub
function gcd(a, b) {
  a = a < 0n ? -a : a;
  b = b < 0n ? -b : b;
  while (b !== 0n) {
    [a, b] = [b, a % b];
  }
  return a;
}

function rat(n, d) {
  if (d === 0n) {
    throw new RangeError("denominator is 0");
  }
  if (d < 0n) {
    n = -n;
    d = -d;
  }
  const g = gcd(n, d);
  return { n: n / g, d: d / g };
}

const add = (a, b) => rat(a.n * b.d + b.n * a.d, a.d * b.d);
const show = (r) => `${r.n}/${r.d}`;

console.log(`rat(6n, -8n): ${show(rat(6n, -8n))}`);
const s = add(rat(1n, 10n), rat(2n, 10n));
console.log(`1/10 + 2/10: ${show(s)}`);
console.log(`0.1 + 0.2: ${0.1 + 0.2}`);
let h = rat(0n, 1n);
for (let k = 1n; k <= 20n; k++) {
  h = add(h, rat(1n, k));
}
console.log(`1/1 + ... + 1/20: ${show(h)}`);
console.log(`as a number: ${Number(h.n) / Number(h.d)}`);
try {
  rat(1n, 0n);
} catch (e) {
  console.log(`rat(1n, 0n): ${e.name}`);
}
Output
rat(6n, -8n): -3/4
1/10 + 2/10: 3/10
0.1 + 0.2: 0.30000000000000004
1/1 + ... + 1/20: 55835135/15519504
as a number: 3.597739657143682
rat(1n, 0n): RangeError
  • Verdict: idiom. JavaScript has no rational type, so the block keeps a pair of bigint values in lowest terms.
  • bigint parts do not overflow, and / on bigint values is exact here, because g divides both parts.
package main

import (
	"fmt"
	"math/big"
)

func main() {
	fmt.Println("NewRat(6, -8):", big.NewRat(6, -8))
	s := new(big.Rat).Add(big.NewRat(1, 10), big.NewRat(2, 10))
	fmt.Println("1/10 + 2/10:", s)
	fmt.Println("RatString:", s.RatString())
	fmt.Println("SetFloat64(0.1):", new(big.Rat).SetFloat64(0.1))
	r, _ := new(big.Rat).SetString("0.1")
	fmt.Println("SetString(\"0.1\"):", r)
	fmt.Println("1/3 FloatString(5):", big.NewRat(1, 3).FloatString(5))
	fmt.Println("2/3 FloatString(5):", big.NewRat(2, 3).FloatString(5))
	defer func() {
		fmt.Println("Quo by 0:", recover())
	}()
	new(big.Rat).Quo(big.NewRat(1, 1), new(big.Rat))
}
Output
NewRat(6, -8): -3/4
1/10 + 2/10: 3/10
RatString: 3/10
SetFloat64(0.1): 3602879701896397/36028797018963968
SetString("0.1"): 1/10
1/3 FloatString(5): 0.33333
2/3 FloatString(5): 0.66667
Quo by 0: division by zero
  • Verdict: stdlib. math/big has Rat, with big.Int parts that do not overflow.
  • SetFloat64 gives the exact value of the float, and SetString reads a decimal string exactly.
  • FloatString rounds the last digit to nearest.
RustGitHub
#[derive(Clone, Copy, Debug, PartialEq)]
struct Ratio {
    n: i64,
    d: i64,
}

fn gcd(mut a: i64, mut b: i64) -> i64 {
    while b != 0 {
        (a, b) = (b, a % b);
    }
    a.abs()
}

fn make(n: i64, d: i64) -> Option<Ratio> {
    if d == 0 {
        return None;
    }
    let (n, d) = if d < 0 { (n.checked_neg()?, d.checked_neg()?) } else { (n, d) };
    let g = gcd(n, d);
    Some(Ratio { n: n / g, d: d / g })
}

fn add(a: Ratio, b: Ratio) -> Option<Ratio> {
    let n = a.n.checked_mul(b.d)?.checked_add(b.n.checked_mul(a.d)?)?;
    let d = a.d.checked_mul(b.d)?;
    make(n, d)
}

fn main() {
    let r = make(6, -8).unwrap();
    println!("make(6, -8): {}/{}", r.n, r.d);
    let s = add(make(1, 10).unwrap(), make(2, 10).unwrap()).unwrap();
    println!("1/10 + 2/10: {}/{}", s.n, s.d);
    println!("make(1, 0): {:?}", make(1, 0));
    let mut h = make(0, 1).unwrap();
    let mut k = 1;
    loop {
        match add(h, make(1, k).unwrap()) {
            Some(next) => h = next,
            None => break,
        }
        k += 1;
    }
    println!("last sum that fits: 1/1 + ... + 1/{} = {}/{}", k - 1, h.n, h.d);
    println!("adding 1/{} overflows i64", k);
}
Output
make(6, -8): -3/4
1/10 + 2/10: 3/10
make(1, 0): None
last sum that fits: 1/1 + ... + 1/43 = 532145396070491417/122332313750680800
adding 1/44 overflows i64
  • Verdict: library. The standard library has no rational type, and the num-rational crate has Ratio, with the aliases Rational64 and BigRational.
  • The block uses i64 parts with checked arithmetic. The sum of 1/k overflows a product of the parts after a few dozen terms, so a long calculation needs bignum parts.
  • Rational literals. Some languages have a syntax for rational values. In J, "1r3 is one-third"1. Julia uses //, as in 6//9 == 2//31, Haskell uses %3, and in Common Lisp 1/3 is a literal of type ratio1.
  • Integer division that gives a rational. In Common Lisp, (/ 6 8) gives 3/41, so the division of two integers is exact. Most languages give a truncated or floored integer, or a float. See Integer division and modulo.
  • Limited-precision rationals. By default, Raku uses its Rat type, which has "rational numbers with limited-precision"1, and its FatRat type "implements arbitrary-precision rational numbers"1.
  • Decimal types. A decimal type is exact for 0.1 but not for 1/3. See Floating-point arithmetic.

Pitfalls

  • Growth of the parts. A loop that adds or multiplies many fractions can make the numerator and the denominator grow at each step, as the first block shows. Each operation then gets slower. Round to a float, or use limit_denominator, when an exact result is not necessary.
  • Overflow with fixed-width parts. A rational type on 64-bit integers can overflow in the product of two denominators, before the GCD reduces it. The Rust example shows this.
  • A float in, a float's value out. Fraction(0.1) is not 1/10. Python warns that "Fraction.from_float(0.3) is not the same value as Fraction(3, 10)"4. Build a rational from integers or from a string.
  • Division by zero. A zero denominator is an error. Python raises ZeroDivisionError4, and Go's Quo panics "If y == 0"6.
  • A rational type does not make a square root exact. The square root of 2 and π are not rational. An operation that leaves the rational numbers, such as a square root, gives a float or an approximation.

Cost

Each addition needs some multiplications of the parts and a GCD to normalize the result, so a rational operation costs many integer operations. With bignum parts, the cost also grows with the length of the parts. See Arbitrary-precision arithmetic. Wikipedia says that the operations "may be translated by the compiler into a sequence of integer machine instructions, or into library calls"1.

History

Common Lisp has the ratio type in its standard2. C++ added compile-time rational arithmetic in the <ratio> header in its 2011 revision1. Python's Fraction constructor accepts float and decimal.Decimal values since version 3.24.

References

  1. Rational data type, Wikipedia, the introduction; Representation; Language support; Common Lisp
  2. System Class RATIO, Common Lisp HyperSpec, Description
  3. Data.Ratio, Haskell base package documentation, Ratio; Rational; numerator
  4. fractions, Rational numbers, The Python Standard Library, class fractions.Fraction; limit_denominator; from_float
  5. num_rational crate documentation, docs.rs, the crate description
  6. big package, math/big, Go standard library, type Rat; SetFloat64; FloatString; Quo
  7. GNU Multiple Precision Arithmetic Library, Wikipedia, the introduction; C++ library interface

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/6JA921/text.yaml