4 ms·
Re floats: True, this problem is universal. I still wish there was a way to circumvent it, much like the arbitrary precision integers circumvent integer proble
by Derbasti 13y ago
Re floats:
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.
- sdevlin 13y agoPython has a decimal package in stdlib. It provides an arbitrary-precision floating point type. The performance will obviously be worse than with floats, but I doubt it matters in an intro programming class. The only real drawback is that there are no decimal literals. Actually, several languages I know of have decimal types in stdlib. Two that do not are C and JavaScript.
- lhl 13y agoWhile obviously it's a fundamental thing to teach/cover the various data types (or at least how '1', 1, and 1.0 are different since they'll be encountering this over and over if they continue programming), on a practical level, frequent casting can be sidestepped by using string formatting when printing numeric output. 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.
- csense 13y agoPython 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.