This module implements rational numbers, consisting of a numerator num and a denominator den, both of type int. The denominator can not be 0.
Rational[T] = object num*, den*: T
proc initRational[T: SomeInteger](num, den: T): Rational[T]
proc `//`[T](num, den: T): Rational[T]
var x = 1//3 + 1//5
proc `$`[T](x: Rational[T]): string
proc toRational[T: SomeInteger](x: T): Rational[T]
proc toRational(x: float; n: int = high(int)): Rational[int] {.raises: [], tags: [].}
Calculate the best rational numerator and denominator that approximates to x, where the denominator is smaller than n (default is the largest possible int to give maximum resolution)
The algorithm is based on the Farey sequence named after John Farey
import math, rationals for i in 1..10: let t = (10 ^ (i+3)).int let x = toRational(PI, t) let newPI = x.num / x.den echo x, " ", newPI, " error: ", PI - newPI, " ", t
proc toFloat[T](x: Rational[T]): float
proc toInt[T](x: Rational[T]): int
proc reduce[T: SomeInteger](x: var Rational[T])
proc `+`[T](x, y: Rational[T]): Rational[T]
proc `+`[T](x: Rational[T]; y: T): Rational[T]
proc `+`[T](x: T; y: Rational[T]): Rational[T]
proc `+=`[T](x: var Rational[T]; y: Rational[T])
proc `+=`[T](x: var Rational[T]; y: T)
proc `-`[T](x: Rational[T]): Rational[T]
proc `-`[T](x, y: Rational[T]): Rational[T]
proc `-`[T](x: Rational[T]; y: T): Rational[T]
proc `-`[T](x: T; y: Rational[T]): Rational[T]
proc `-=`[T](x: var Rational[T]; y: Rational[T])
proc `-=`[T](x: var Rational[T]; y: T)
proc `*`[T](x, y: Rational[T]): Rational[T]
proc `*`[T](x: Rational[T]; y: T): Rational[T]
proc `*`[T](x: T; y: Rational[T]): Rational[T]
proc `*=`[T](x: var Rational[T]; y: Rational[T])
proc `*=`[T](x: var Rational[T]; y: T)
proc reciprocal[T](x: Rational[T]): Rational[T]
proc `/`[T](x, y: Rational[T]): Rational[T]
proc `/`[T](x: Rational[T]; y: T): Rational[T]
proc `/`[T](x: T; y: Rational[T]): Rational[T]
proc `/=`[T](x: var Rational[T]; y: Rational[T])
proc `/=`[T](x: var Rational[T]; y: T)
proc cmp(x, y: Rational): int {.procvar.}
proc `<`(x, y: Rational): bool
proc `<=`(x, y: Rational): bool
proc `==`(x, y: Rational): bool
proc abs[T](x: Rational[T]): Rational[T]
proc hash[T](x: Rational[T]): Hash
© 2006–2017 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/rationals.html