[swift-users] A sample Rational number type
hooman at mac.com
Fri Sep 30 21:46:19 CDT 2016
For anybody who is interested: This gist <https://gist.github.com/hooman/6e08c48e1e06ee19e06e5b09f664f9be> contains a Rational number implementation for Swift 3.0. It is a single file that you can paste in a playground and take a look, or remove the last few lines and drop the file into your own module. The recommended way to create a rational number is specifying Rational type as in:
let r: Rational = 18/64
let x = 5 + 2/3 as Rational
or use tolerance operator `±` to convert from floating point:
let r2 = 2.109±0.0005 // 2⁷⁄₆₄
Rational type conforms to AbsoluteValuable (hence Equatable, Comparable, ExpressibleByIntegerLiteral, SignedNumber), Strideable, and CustomStringConvertible.
It always uses fully-reduced representation for simplicity and clarity of comparisons and uses LCM (lowest common multiple) for addition & subtraction to reduce the chance of overflow in the middle of computations. The disadvantage of these design choices are: It is not guaranteed to keep the nominator and denominator as specified during construction, and GCD / LCM computations reduce its performance.
The performance trade-off is not huge and is usually acceptable for typical rational number use cases. Preserving denominator can be addressed with a number formatter for rational numbers that I will add later. GCD is computed with Stein's algorithm (binary GCD algorithm).
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-users