Rationals Lib
dsimcha
dsimcha at yahoo.com
Sat Oct 10 19:56:10 PDT 2009
I've created a small D2 lib for performing operations on rational numbers.
It's templated to work on any integer type that supports the relevant
operators. Usually this would be used with some type of arbitrary precision
integer. It can work with fixed-size integers, though overflows would be
generated fairly easily when adding several rational numbers with different
denominators, or multiplying several without very many common factors.
The lib is available at:
http://dsource.org/projects/scrapple/browser/trunk/rational/rational.d
A simple usage example is:
import std.bigint, rational;
void main() {
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);
}
More information about the Digitalmars-d-announce
mailing list