Implementing fractions
module from The Python Standard Library on TypeScript.
npm i fractions-math
yarn add fractions-math
import { Fraction, fraq } from "fractions-math"
const f1 = new Fraction(1, 2)
const f2 = fraq(1.5)
const f3 = f1.add(f2).toString() // -> "2" (0.5 + 1.5)
const f4 = f3.mul(f2).toString() // -> "3" (2 * 1.5)
const f5 = f4.div(f1).toString() // -> "6" (3 / 0.5)
type Fraq = Fraction | [number, number] | number | string
Helper function to create fraction from various inputs.
fraq(2).toPair() // -> [2, 1]
fraq([2, 1]).toPair() // -> [2, 1]
fraq(0.5).toPair() // -> [1, 2]
fraq("1/2").toPair() // -> [1, 2]
Creates a fraction taking two numbers β numenator and denominator. Denominator has default value 1
. By default, the fraction is reduced to the minimum form.
new Fraction(1, 2).toPair() // -> [1, 2]
new Fraction(2).toPair() // -> [2, 1]
new Fraction(5, 10).toPair() // -> [5, 10]
new Fraction(5, 10, true).toPair() // -> [1, 2]
fraq(1, 2).toString() // -> "1/2"
fraq(3, 3).toString() // -> "3"
fraq(-1).toString() // -> "-1"
fraq(1, -2).toString() // -> "-1/2"
fraq(1, 2).toString() // -> 0.5
fraq(5, 10).reduce().toPair() // -> [1, 2]
Finds the closest Fraction that has denominator at most max
.
fraq(Math.PI).limit(1000).toString() // -> "355/113"
fraq(1.1).limit().toString() // -> "11/10"
fraq(1, 2).add([-1, 2]).toString() // -> "0"
fraq(1, 2).add(1).toString() // -> "3/2"
fraq(1, 2).sub([1, 2]).toString() // -> "0"
fraq(1, 2).sub(1).toString() // -> "-1/2"
fraq(1, 2).mul([1, 2]).toString() // -> "1/4"
fraq(1, 2).mul(1.5).toString() // -> "3/4"
fraq(1, 2).div([1, 2]).toString() // -> "1"
fraq(1, 2).div(1.5).toString() // -> "1/3"
fraq(1, 2).div(0).toString() // throws Error
fraq(1, 2).eq(0.5) // -> true
fraq(1, 2).eq([1, 3]) // -> false
fraq(0.5).toUnicode() // -> "1/2"
fraq([1, 64]).toUnicode() // -> "0"
fraq([1, 64]).toUnicode(64) // -> "1/64"
fraq(0.5).toUnicode() // -> "Β½"
fraq([1, 64]).toUnicode() // -> "0"
fraq([1, 64]).toUnicode(64) // -> "ΒΉβββ"