[swift-users] A sample Rational number type
hooman at mac.com
Mon Oct 3 01:48:26 CDT 2016
> On Oct 2, 2016, at 5:23 PM, Dave Abrahams via swift-users <swift-users at swift.org> wrote:
> Presumably you mean:
> let r2 = r±0.0005 // turn a Rational into a Double with no more than
> // .0005 rounding error
> ? That is supercute!
It is actually the other way around: It returns a rational given a double so that the maximum difference of the created rational with the input double is the specified tolerance.
> Have you thought about what this would look like after we land
> https://github.com/apple/swift/pull/3796 (see
That is the next thing I want to look at, the next chance I get. For now, it isn’t much more than a quick hack on a slow Friday…
> You can also find a working prototype of that code at
> It would be great to know that the protocols we've designed actually
> work out for Rational numbers. With these protocols, can you make your
> Rational generic on the underlying integer type?
> There's a BigInt implementation based on these protocols here:
> It would be really cool to see it work with a generic version of your
> Rational type.
Interesting idea. A BigInt type can really lift Rational to new levels. Interesting case study to see how well the new protocols work.
> It's interesting to see that one wants a different algorithm for GCD
> when using BigInts:
> I wonder how that should be dispatched…
Moreover, there is something I ran into after posting: On today’s CPU architectures with fast integer divide, simple binary CGD is slower than basic Euler’s algorithm using remainders. Binary GCD needs the equivalent of __builtin_ctz to run faster. It would be nice if compiler could detect the shift loops and replace the whole loop with x86 BSFL instruction.
I need to put some thought on whether there is an efficient means of switching the algorithm based on the actual size (or nature) of the given Int type, otherwise we may have to specialize, which is not good from a generics standpoint.
More information about the swift-users