[swift-users] A sample Rational number type
Hooman Mehr
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
// or
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).
Hooman
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160930/06236783/attachment.html>
More information about the swift-users
mailing list