record Fraction

record Fraction(num: int, den: int)

← Index

Fraction — exact rational arithmetic

A Fraction is a rational number num / den kept in lowest terms with a positive denominator. Being exact, it sidesteps the rounding error of floating point:

val third = Fraction::of(1, 3)
val whole = third + third + third   // exactly 1/1, not 0.999...

Operator methods (plus, minus, times, div) back + - * / directly, and toDouble crosses over to floating point when you need it.

Methods

static def of(n: int, d: int): Fraction

Builds a normalized fraction n / d, reduced with a positive denominator.

Parameters
n — the numerator
d — the denominator; must be non-zero
Returns
the reduced fraction
Throws
IllegalArgumentException — if `d` is zero
def plus(o: Fraction): Fraction

Adds o to this fraction. Backs the + operator.

def minus(o: Fraction): Fraction

Subtracts o from this fraction. Backs the - operator.

def times(o: Fraction): Fraction

Multiplies this fraction by o. Backs the * operator.

def toDouble(): double

The closest Double to this exact value.

def show(): String

Renders the fraction as num/den.

static def gcd(a: int, b: int): int

Fields

num: int

Fraction — exact rational arithmetic

A Fraction is a rational number num / den kept in lowest terms with a positive denominator. Being exact, it sidesteps the rounding error of floating point:

val third = Fraction::of(1, 3)
val whole = third + third + third   // exactly 1/1, not 0.999...

Operator methods (plus, minus, times, div) back + - * / directly, and toDouble crosses over to floating point when you need it.

den: int

Fraction — exact rational arithmetic

A Fraction is a rational number num / den kept in lowest terms with a positive denominator. Being exact, it sidesteps the rounding error of floating point:

val third = Fraction::of(1, 3)
val whole = third + third + third   // exactly 1/1, not 0.999...

Operator methods (plus, minus, times, div) back + - * / directly, and toDouble crosses over to floating point when you need it.