This module implements rational numbers, consisting of a numerator and a denominator. The denominator can not be 0.
Example:
import std/rationals let r1 = 1 // 2 r2 = -3 // 4 doAssert r1 + r2 == -1 // 4 doAssert r1 - r2 == 5 // 4 doAssert r1 * r2 == -3 // 8 doAssert r1 / r2 == -2 // 3
Procs
func `//`[T](num, den: T): Rational[T]
-
A friendlier version of initRational.
Example:
let x = 1 // 3 + 1 // 5 doAssert x == 8 // 15
Source Edit func `^`[T: SomeInteger](x: Rational[T]; y: T): Rational[T]
-
Computes x to the power of y.
The exponent y must be an integer. Negative exponents are supported but floating point exponents are not.
Example:
doAssert (-3 // 5) ^ 0 == (1 // 1) doAssert (-3 // 5) ^ 1 == (-3 // 5) doAssert (-3 // 5) ^ 2 == (9 // 25) doAssert (-3 // 5) ^ -2 == (25 // 9)
Source Edit func `div`[T: SomeInteger](x, y: Rational[T]): T
- Computes the rational truncated division. Source Edit
func floorDiv[T: SomeInteger](x, y: Rational[T]): T
-
Computes the rational floor division.
Floor division is conceptually defined as floor(x / y). This is different from the div operator, which is defined as trunc(x / y). That is, div rounds towards 0 and floorDiv rounds down.
Source Edit func initRational[T: SomeInteger](num, den: T): Rational[T]
-
Creates a new rational number with numerator num and denominator den. den must not be 0.
Note: den != 0 is not checked when assertions are turned off.
Source Edit func reciprocal[T](x: Rational[T]): Rational[T]
- Calculates the reciprocal of x (1/x). If x is 0, raises DivByZeroDefect. Source Edit
func reduce[T: SomeInteger](x: var Rational[T])
-
Reduces the rational number x, so that the numerator and denominator have no common divisors other than 1 (and -1). If x is 0, raises DivByZeroDefect.
Note: This is called automatically by the various operations on rationals.
Example:
var r = Rational[int](num: 2, den: 4) # 1/2 reduce(r) doAssert r.num == 1 doAssert r.den == 2
Source Edit func toRational(x: float; n: int = high(int) shr 32): Rational[int] {. ...raises: [], tags: [], forbids: [].}
-
Calculates the best rational approximation of x, where the denominator is smaller than n (default is the largest possible int for maximal resolution).
The algorithm is based on the theory of continued fractions.
Example:
let x = 1.2 doAssert x.toRational.toFloat == x
Source Edit func toRational[T: SomeInteger](x: T): Rational[T]
-
Converts some integer x to a rational number.
Example:
doAssert toRational(42) == 42 // 1
Source Edit