rational

Implements rational numbers on top of whatever integer type is specified by the user. The integer type used may be any type that behaves as an integer. Specifically, isIntegerLike must return true, the integer type must have value semantics, and the semantics of all integer operations must follow the normal rules of integer arithmetic.

A regular integer can be converted to rational type simply by passing it as a single argument. In this case the denominator will simply be set to 1.

  1. Rational!(CommonInteger!(I1, I2)) rational(I1 i1, I2 i2)
    Rational!(CommonInteger!(I1, I2))
    rational
    (
    I1
    I2
    )
    (
    I1 i1
    ,
    I2 i2
    )
  2. Rational!(I) rational(I val)

Examples

auto r1 = rational(BigInt("314159265"), BigInt("27182818"));
auto r2 = rational(BigInt("8675309"), BigInt("362436"));
r1 += r2;
assert(r1 == rational(BigInt("174840986505151"),
					   BigInt("4926015912324")));

// Print result.  Prints:
// "174840986505151/4926015912324"
writeln(r1);

// Print result in decimal form.  Prints:
// "35.4934"
writeln(cast(real) r1);

auto r3 = rational(10);
assert(r3.numerator == 10);
assert(r3.denominator == 1);
assert(r3 == 10);

Meta