RatMath Logo

RatMath Library

JavaScript library for exact rational arithmetic using BigInt

Key Features

๐ŸŽฏ Exact Arithmetic

No floating-point errors. Every calculation maintains perfect precision using BigInt internally.

// JavaScript floats
0.1 + 0.2 === 0.3  // false!

// RatMath
R`0.1 + 0.2`.equals(R`0.3`)  // true!

๐Ÿ“Š Interval Arithmetic

Built-in support for interval calculations, perfect for uncertainty analysis.

// Create intervals
const a = R`1:2`      // [1, 2]
const b = R`0.5:1.5`  // [0.5, 1.5]

// Operations preserve bounds
R`1:2 + 0.5:1.5`  // [1.5, 3.5]

๐Ÿ”ข Type System

Smart type promotion: Integer โ†’ Rational โ†’ RationalInterval as needed.

R`5 + 7`        // Integer(12)
R`5 / 2`        // Rational(5/2)
R`5 + 1:2`      // RationalInterval([6, 7])

๐ŸŽจ Rich Notation

Support for mixed numbers, repeating decimals, continued fractions, and more.

R`2..1/3`    // Mixed: 2 and 1/3
R`0.#3`      // Repeating: 0.333... = 1/3
R`3.~7~15~1` // Continued fraction = 355/113

Interactive Examples

Basic Arithmetic

Repeating Decimals

Interval Operations

Continued Fractions

Code Playground

Try the RatMath API directly in your browser. Press Ctrl+Enter (or Cmd+Enter) to run code:

API Quick Reference

Creating Numbers

R\`1/2\`         // Rational
R\`42\`          // Integer
R\`1:2\`         // Interval
F\`3/4\`         // Fraction (no reduction)

Operations

.add(other)
.subtract(other)
.multiply(other)
.divide(other)
.pow(n)

Comparisons

.equals(other)
.lessThan(other)
.greaterThan(other)
.lessThanOrEqual(other)
.greaterThanOrEqual(other)

Conversions

.toString()
.toDecimal(limit)
.toMixed()
.toContinuedFraction()
.toScientific(precision)

Installation

NPM

npm install ratmath

Bun

bun add ratmath

Browser (ES Modules)

<script type="module">
  import { R, F } from './ratmath.js';
  // Your code here
</script>

Basic Usage

import { R, Parser } from 'ratmath';

// Using template literals with expressions
const sum = R\`1/3 + 2/3\`;  // Rational(1)

// Or using method calls
const third = R\`1/3\`;
const twoThirds = R\`2/3\`;
const sum2 = third.add(twoThirds);  // Rational(1)

// Using Parser directly
const expr = Parser.parse("1/2 + 1/3");  // Rational(5/6)

// Working with intervals
const measurement = R\`5.2[+-0.05]\`;  // [5.15, 5.25]