Jump to content

Arithmetic/Rational: Difference between revisions

Updated D entry
(Added constructor in the D entry)
(Updated D entry)
Line 371:
 
// std.numeric.gcd doesn't work with BigInt.
T gcd(T)(in T a, in T b) pure /*nothrow*/ {
return (b != 0) ? gcd(b, a % b) : (a < 0) ? -a : a;
}
 
T lcm(T)(in T a, in T b) pure /*nothrow*/ {
return a / gcd(a, b) * b;
}
Line 398:
}
 
this(U, V)(in U n, in V d) pure /*nothrow*/ {
num = toT(n);
den = toT(d);
Line 441:
}
 
real toReal() pure const /*nothrow*/ {
static if (is(T == BigInt))
return num.toLong / real(den.toLong);
Line 449:
 
RationalT opBinary(string op)(in RationalT r)
const pure /*nothrow*/ if (op == "+" || op == "-") {
T common = lcm(den, r.den);
T n = mixin("common / den * num" ~ op ~
Line 457:
 
RationalT opBinary(string op)(in RationalT r)
const pure /*nothrow*/ if (op == "*") {
return RationalT(num * r.num, den * r.den);
}
 
RationalT opBinary(string op)(in RationalT r)
const pure /*nothrow*/ if (op == "/") {
return RationalT(num * r.den, den * r.num);
}
 
RationalT opBinary(string op, U)(in U r)
const pure /*nothrow*/ if (isIntegral!U && (op == "+" ||
op == "-" || op == "*" || op == "/")) {
return opBinary!op(RationalT(r));
Line 473:
 
RationalT opBinary(string op)(in size_t p)
const pure /*nothrow*/ if (op == "^^") {
return RationalT(num ^^ p, den ^^ p);
}
 
RationalT opBinaryRight(string op, U)(in U l)
const pure /*nothrow*/ if (isIntegral!U) {
return RationalT(l).opBinary!op(RationalT(num, den));
}
Line 488:
 
RationalT opUnary(string op)()
const pure /*nothrow*/ if (op == "+" || op == "-") {
return RationalT(mixin(op ~ "num"), den);
}
Line 503:
}
 
int opCmp(U)(in U r) const pure nothrow {
auto rhs = RationalT(r);
if (type() == Type.NaRAT || rhs.type() == Type.NaRAT)
throw new ExceptionError("Compare involve a NaRAT.");
if (type() != Type.NORMAL ||
rhs.type() != Type.NORMAL) // for infinite
Line 524:
}
 
RationalT!U rational(U)(in U n) pure /*nothrow*/ {
return typeof(return)(n);
}
 
RationalT!(CommonType!(U1, U2))
rational(U1, U2)(in U1 n, in U2 d) pure /*nothrow*/ {
return typeof(return)(n, d);
}
Cookies help us deliver our services. By using our services, you agree to our use of cookies.