Rationals Lib?

dsimcha dsimcha at yahoo.com
Sat Oct 10 19:51:45 PDT 2009


== Quote from dsimcha (dsimcha at yahoo.com)'s article
> == Quote from language_fan (foo at bar.com.invalid)'s article
> > Sat, 10 Oct 2009 21:29:41 +0000, dsimcha thusly wrote:
> > > I guess I could have implemented some of these suggestions, but the idea
> > > was for this lib to be very simple (it's only about 300 lines of code so
> > > far) and agnostic to the implementation of the integers it's working on
> > > top of, with the caveat that, if you use something that's not arbitrary
> > > precision, the onus is on you to make sure nothing overflows.  If
> > > anyone, for example, made a wrapper to the GNU multiprecision lib that
> > > looked like a D struct w/ operator overloading, it would be able to plug
> > > right into this library.  If std.bigint improves, this library will
> > > automatically benefit.
> > Now that's the most perfect way to test the modularity of the language --
> > does it allow implementing a rational library on top of any (arbitrary
> > precision) number type, assuming we have a sane interface to work with.
> Save for a few small details, yes.  Since there seems to be interest I'll clean up
> the code and post it somewhere in the next few days.  Here are the "few details":
> 1.  To convert to floating-point form, I need to be able to cast the underlying
> arbitrary precision integers to machine-native types.  There's no standard way to
> do this.
> 2.  I need a standard way of constructing any type of integer, whether
> machine-native or arbitrary precision, to implement some syntactic sugar features.
>  Let's say you wanted the number 314 as a rational, with a std.bigint.BigInt as
> the underlying integer.  Right now you'd have to do:
> auto foo = fraction( BigInt(314), BigInt(1));
> There's no shortcut yet for when you want a whole number to be represented
> internally as a fraction because there's no standard way to construct any
> arbitrary integer type with the value 1.
> The same problem applies to conversion from floating-point to rational and
> comparison between rational and integer.

Ok, I got it to work.  I even found kludges around the issues I raised previously:

1.  To convert an arbitrary BigInt to a long, use binary search and equality
testing.  It's slow, but converting a BigInt fraction to a float is slow anyhow.

2.  Just implement completely separate overloads for when one of the operands is
an int.

See http://dsource.org/projects/scrapple/browser/trunk/rational/rational.d .



More information about the Digitalmars-d mailing list