Fraction & Mixed Number Calculator
Add, subtract, multiply, and divide proper, improper, and mixed fractions with step-by-step reduction and GCD.
Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.
Arithmetic & Number-Theoretic Foundations of Fractions
A Fraction Calculator performs exact rational arithmetic across proper fractions, improper fractions, and mixed numbers without introducing rounding artifacts or precision loss. In formal mathematics, the field of rational numbers $\mathbb{Q}$ is defined as the quotient of two integers:
$$\mathbb{Q} = \left{ \frac{a}{b} ;\middle|; a, b \in \mathbb{Z},, b \neq 0 \right}$$
Where:
- $a$ is the numerator (representing the quantity of fractional parts).
- $b$ is the denominator (representing the total number of equal parts comprising the integer unit).
+---------------------------------------------------------------------------------------------------+
| FRACTION CLASSIFICATION TAXONOMY |
+---------------------------------------------------------------------------------------------------+
| PROPER FRACTIONS IMPROPER FRACTIONS MIXED NUMBERS |
| |a| < |b| |a| >= |b| Integer + Proper Fraction |
| Example: 3/4, -5/8 Example: 7/4, 11/3 Example: 1 3/4, -2 1/3 |
| Magnitude: 0 <= |x| < 1 Magnitude: |x| >= 1 Canonical Human Representation |
+---------------------------------------------------------------------------------------------------+
|
v
+---------------------------------------------------------------------------------------------------+
| CANONICAL IRREDUCIBLE FORM (LOWEST TERMS) |
| Divide numerator and denominator by Greatest Common Divisor: gcd(a, b) |
| Example: 42 / 56 ---> gcd(42, 56) = 14 ---> (42/14) / (56/14) = 3 / 4 |
+---------------------------------------------------------------------------------------------------+
The Euclidean Algorithm for Greatest Common Divisor (GCD)
To reduce any fraction $a/b$ to its unique, irreducible canonical form, both components must be divided by their Greatest Common Divisor (GCD). The Euclidean Algorithm calculates the GCD of two integers in logarithmic time $\mathcal{O}(\log(\min(|a|, |b|)))$:
$$\gcd(a, 0) = |a|$$ $$\gcd(a, b) = \gcd(b, a \bmod b)$$
Once $\gcd(a, b)$ is determined, the Least Common Multiple (LCM) (essential for finding the Lowest Common Denominator in addition and subtraction) is derived via:
$$\text{lcm}(a, b) = \frac{|a \times b|}{\gcd(a, b)}$$
Mathematical Formulas & Step-by-Step Mechanics
ARITHMETIC OPERATIONS ON FRACTIONS
ADDITION / SUBTRACTION: (a/b) ± (c/d) = (a·d ± c·b) / (b·d)
MULTIPLICATION: (a/b) · (c/d) = (a·c) / (b·d)
DIVISION: (a/b) ÷ (c/d) = (a·d) / (b·c)
1. Addition and Subtraction
When denominators differ ($b \neq d$), fractions cannot be summed directly. Two algebraic methods exist:
- Cross-Multiplication Method: $$\frac{a}{b} \pm \frac{c}{d} = \frac{a \cdot d \pm c \cdot b}{b \cdot d}$$
- Least Common Denominator (LCD) Method: Compute $L = \text{lcm}(b, d)$. Scale numerators by $L/b$ and $L/d$: $$\frac{a}{b} \pm \frac{c}{d} = \frac{a \cdot (L / b) \pm c \cdot (L / d)}{L}$$ The LCD method generates significantly smaller intermediate integers, preventing integer overflow in large calculations.
2. Multiplication
Multiplication requires no common denominator. Numerators and denominators multiply directly:
$$\frac{a}{b} \times \frac{c}{d} = \frac{a \times c}{b \times d}$$
Prior to multiplying, terms can be cross-simplified: divide $\gcd(a, d)$ out of $a$ and $d$, and divide $\gcd(c, b)$ out of $c$ and $b$.
3. Division (Invert and Multiply)
Division by a rational number is equivalent to multiplication by its multiplicative inverse (reciprocal):
$$\frac{a}{b} \div \frac{c}{d} = \frac{a}{b} \times \frac{d}{c} = \frac{a \times d}{b \times c} \quad (c \neq 0)$$
4. Mixed Number Conversions
- Mixed to Improper: $$W \frac{N}{D} = \frac{W \times D + N}{D}$$
- Improper to Mixed: For improper fraction $A / B$ where $A \ge B$: $$W = \lfloor A / B \rfloor, \quad \text{Remainder } R = A \bmod B \implies W \frac{R}{B}$$
Production Code Implementation
Standard IEEE 754 floating-point hardware produces infamous rounding anomalies (such as $0.1 + 0.2 = 0.30000000000000004$). Production rational arithmetic engines enforce infinite precision by maintaining distinct numerator and denominator integer representations.
Python: Full-Featured Rational Arithmetic Class
#!/usr/bin/env python3
"""
Zero-drift Exact Rational Number Class supporting Proper, Improper,
and Mixed Fraction Arithmetic with Canonical Sign and Lowest-Terms Reduction.
"""
from typing import Union, Tuple
class Rational:
def __init__(self, numerator: int, denominator: int = 1):
if denominator == 0:
raise ZeroDivisionError("Denominator cannot be zero in rational arithmetic.")
# Enforce canonical sign: denominator is strictly positive
if denominator < 0:
numerator = -numerator
denominator = -denominator
self.n = numerator
self.d = denominator
self._reduce()
def _gcd(self, a: int, b: int) -> int:
"""Euclidean algorithm for greatest common divisor."""
while b != 0:
a, b = b, a % b
return abs(a)
def _reduce(self) -> None:
"""Divides numerator and denominator by their GCD."""
g = self._gcd(self.n, self.d)
if g > 1:
self.n //= g
self.d //= g
def __add__(self, other: "Rational") -> "Rational":
# a/b + c/d = (a*d + c*b) / (b*d)
num = self.n * other.d + other.n * self.d
den = self.d * other.d
return Rational(num, den)
def __sub__(self, other: "Rational") -> "Rational":
num = self.n * other.d - other.n * self.d
den = self.d * other.d
return Rational(num, den)
def __mul__(self, other: "Rational") -> "Rational":
num = self.n * other.n
den = self.d * other.d
return Rational(num, den)
def __truediv__(self, other: "Rational") -> "Rational":
if other.n == 0:
raise ZeroDivisionError("Cannot divide by a fraction equal to zero.")
num = self.n * other.d
den = self.d * other.n
return Rational(num, den)
def to_mixed(self) -> Tuple[int, int, int]:
"""Returns (whole_integer, numerator, denominator) for mixed format."""
whole = self.n // self.d
rem = abs(self.n % self.d)
return whole, rem, self.d
def to_decimal(self, places: int = 6) -> str:
"""Formats the fraction to a fixed-precision decimal representation."""
val = self.n / self.d
return f"{val:.{places}f}"
def __repr__(self) -> str:
if self.d == 1:
return str(self.n)
return f"{self.n}/{self.d}"
# Demonstration
if __name__ == "__main__":
# Calculate: 3/4 + 5/6 - (1/2 * 2/3) / (3/5)
f1 = Rational(3, 4)
f2 = Rational(5, 6)
f3 = Rational(1, 2)
f4 = Rational(2, 3)
f5 = Rational(3, 5)
sum_res = f1 + f2
mul_res = f3 * f4
div_res = mul_res / f5
final_res = sum_res - div_res
print(f"3/4 + 5/6 = {sum_res} (Mixed: {sum_res.to_mixed()[0]} {sum_res.to_mixed()[1]}/{sum_res.to_mixed()[2]})")
print(f"(1/2 * 2/3) / (3/5) = {div_res}")
print(f"Final Expression Result = {final_res}")
print(f"Decimal Equivalent = {final_res.to_decimal(6)}")
TypeScript: BigInt Precision Fraction Engine
/**
* Arbitrary-precision Rational Number Engine powered by native ES2020 BigInt
* completely immune to 64-bit IEEE 754 precision loss.
*/
export class Fraction {
public readonly num: bigint;
public readonly den: bigint;
constructor(numerator: bigint | number, denominator: bigint | number = 1n) {
let n = BigInt(numerator);
let d = BigInt(denominator);
if (d === 0n) {
throw new Error("ZeroDivisionError: Denominator cannot be zero.");
}
if (d < 0n) {
n = -n;
d = -d;
}
const gcdVal = Fraction.gcd(n < 0n ? -n : n, d);
this.num = n / gcdVal;
this.den = d / gcdVal;
}
private static gcd(a: bigint, b: bigint): bigint {
while (b !== 0n) {
const temp = b;
b = a % b;
a = temp;
}
return a;
}
public add(other: Fraction): Fraction {
return new Fraction(
this.num * other.den + other.num * this.den,
this.den * other.den
);
}
public subtract(other: Fraction): Fraction {
return new Fraction(
this.num * other.den - other.num * this.den,
this.den * other.den
);
}
public multiply(other: Fraction): Fraction {
return new Fraction(this.num * other.num, this.den * other.den);
}
public divide(other: Fraction): Fraction {
if (other.num === 0n) {
throw new Error("ZeroDivisionError: Cannot divide by zero.");
}
return new Fraction(this.num * other.den, this.den * other.num);
}
public toString(): string {
return this.den === 1n ? `${this.num}` : `${this.num}/${this.den}`;
}
public toDecimal(decimals: number = 6): string {
const factor = 10n ** BigInt(decimals);
const scaled = (this.num * factor) / this.den;
const isNegative = scaled < 0n;
const absStr = (isNegative ? -scaled : scaled).toString().padStart(decimals + 1, "0");
const intPart = absStr.slice(0, -decimals) || "0";
const decPart = absStr.slice(-decimals);
return `${isNegative ? "-" : ""}${intPart}.${decPart}`;
}
}
Numerical Representation Comparison Matrix
| Representation | Precision Model | Representation of $1/3$ | Memory Footprint | Algebraic Closure ($\mathbb{Q}$) | Execution Speed |
|---|---|---|---|---|---|
| Exact Rational ($\mathbb{Q}$) | Absolute (Infinite) | $1/3$ (Exact) | Dynamic ($2 \times \text{BigInt}$) | Fully Closed under $+,-,\times,\div$ | Microsecond (GCD overhead) |
| IEEE 754 Double (64-bit) | 53 bits mantissa (~15-17 sig digs) | $0.3333333333333333...$ (Lossy) | Fixed 8 bytes | Not Closed (Rounding drift) | Hardware Nanosecond |
| Fixed-Point Decimal | Configurable decimal scaling | $0.3333$ (Truncated) | Moderate | Not Closed on division | Fast (Integer CPU op) |
| Continued Fractions | Infinite sequence expansion | $[0; 3]$ (Exact) | Dynamic list | Fully Closed | Moderate |
Critical Numerical Edge Cases & Traps
1. The Denominator Zero Singularity
In mathematics, division by zero ($\frac{a}{0}$) is undefined. Within computer science:
- A zero denominator produces an indeterminate form ($\frac{0}{0}$) or an infinite limit ($\pm \infty$).
- Production fraction tools must validate user inputs upfront and throw explicit exceptions rather than allowing silent
NaNor unhandled exceptions to crash the calculation stack.
2. Intermediate Integer Overflow in Cross-Multiplication
When evaluating:
$$\frac{a}{b} + \frac{c}{d} = \frac{a \cdot d + c \cdot b}{b \cdot d}$$
If $a, b, c, d$ are 32-bit or 64-bit integers, the products $a \cdot d$ and $b \cdot d$ can overflow hardware integer registers before the final GCD reduction occurs, leading to silent sign inversion.
- Remediation: In languages like C/C++ or Rust, operations must evaluate intermediate products in double-width registers (e.g.,
__int128) or compute LCD first: $L = \text{lcm}(b, d)$. In modern high-level languages like Python or TypeScript (withBigInt), arbitrary-width integers prevent overflow natively.
3. Canonical Sign Invariance
A fraction can be written in multiple signed permutations: $\frac{-3}{4}$, $\frac{3}{-4}$, and $-\frac{3}{4}$ all represent the exact same rational value.
- Canonical normalization rules mandate that the denominator must always be strictly positive ($b > 0$).
- If a negative denominator is introduced, both numerator and denominator must be multiplied by $-1$:
$$\frac{a}{-b} \implies \frac{-a}{b}$$
4. Recurring Decimals and Periodicity
Converting rational numbers to decimal format introduces repeating periodic cycles (e.g., $1/7 = 0.\overline{142857}$). According to Dirichlet's box principle, for any denominator $d$ coprime to 10, the length of the repetend period divides Euler's totient $\phi(d)$. Fraction utilities displaying decimal expansions must either round explicitly to a user-selected precision or detect repetends to display bracketed repeating periods.