3 ms·
Python has the "fractions" module which provides a more powerful abstraction: It's not restricted to denominators that are powers of 10. > I don't know their
by csense 13y ago
Python has the "fractions" module which provides a more powerful abstraction: It's not restricted to denominators that are powers of 10.
> 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.