Rational

Reduced-form rational number.

NOTE: The implementation does NOT attempt to handle overflows. Use a custom type for that.

Constructors

this
this(inout(Z) numerator, inout(Z) denominator)

Constructs a Rational from given numerator and (non-zero) denominator.

Members

Functions

opAssign
void opAssign(Z numerator)

Assigns an integer value to this rational number.

opBinary
Rational opBinary(const(Rational) rhs)
Rational opBinary(Z rhs)
opBinaryRight
Rational opBinaryRight(Z lhs)

Arithmetic operations on rationals and/or integers.

opCast
N opCast()

Casts rational to a scalar (may lose precision).

opCmp
int opCmp(const(Rational) rhs)
int opCmp(Z rhs)

Compares two rationals based on their reduced form.

opCmp
int opCmp(R rhs)

Casts and compares rational with floating-point type.

opEquals
bool opEquals(const(Rational) rhs)
bool opEquals(Z rhs)

Compares two rationals based on their reduced form.

opEquals
bool opEquals(R rhs)

Casts and compares rational with floating-point type.

opUnary
Rational opUnary()

Unary negation.

Properties

denominator
Z denominator [@property getter]

Reduced-form denominator, always positive.

numerator
Z numerator [@property getter]

Reduced-form numerator.

Examples

// rationals can store fractional numbers without precision loss
alias Ratio = Rational!long;
auto r = Ratio(3, 4);
assert(r.numerator == 3);
assert(r.denominator == 4);

// but remember that they are always kept in reduced form
assert(Ratio(6, 4) == Ratio(3, 2));
auto r2 = -(r * 2);
assert(r2.numerator == -3); // numerator may be negative
assert(r2.denominator == 2); // but denominator is always positive

// they can be compared with floating-point and integral numbers
assert(r == 0.75 && 0.75 == r);
assert(r != 1 && 1 != r);
assert(r < 1 && 1 > r);
assert(r2 <= -1.5 && -1.5 >= r2);
assert(r > r2);

// arithmetic and casts work as expected (modulo overflows)
assert(Ratio(-3, 5) + Ratio(2, 3) == Ratio(1, 15));
assert(Ratio(-3, 14) - Ratio(5, 7) == Ratio(-13, 14));
assert(Ratio(3, 7) * Ratio(7, 3) == 1 && 1 == Ratio(3, 7) * Ratio(7, 3));
assert(Ratio(7, 3) / Ratio(2, 3) == Ratio(7, 2));
assert(cast(int)(2 * (1 + Ratio(42) - 1) / 2) == 42);