by Derbasti · 12y ago · 0 comments
True, this problem is universal. I still wish there was a way to circumvent it, much like the arbitrary precision integers circumvent integer problems. Rationals and fractional integers come to mind, though I don't know their performance characteristics.
> I don't know their performance characteristics
It's easy to make some good guesses.
Since (I'm guessing) it's implemented with pairs of integers, adding probably uses
a / b + c / d = (ad + bc) / (cd)
which is 3 multiplications and an addition, and multiplication probably uses (a / b) (c / d) = (ac) / (bd)
so only two multiplications. So it's a small constant factor times the cost of integer multiplication, plus a bit of overhead for the wrapper class.So my back-of-the-envelope guess is that the fractions module is less than 10x slower than the same operation with integers, or fast enough for just about anything you do in a beginner level class.
These numbers will change significantly if fractions are automatically reduced by gcd of numerator and denominator; I'm not sure about this point.
Actually, several languages I know of have decimal types in stdlib. Two that do not are C and JavaScript.
In all my production code (my string printing is not performance critical) I pretty much always use string substitution when printing as a matter of style/convenience. It's much easier to add/replace substitutions, and I often need formatting anyway.
If students get used to printing w/ string substitution, they can then simply use %d or %f to control how they want their numbers to display, which is probably the right way of thinking about rendering text output.