in reply to floating point addition
This is also the reason why processors have a “decimal mode,” in which both digits and the sign of the number are represented using four-bit groups (so-called “binary-coded decimal = BCD.”). The COBOL language is famous for exposing this feature, and for very obvious reasons: when dollars-and-cents are involved, accountants (especially) care very much about “cents.” The arithmetic will be performed in true decimal mode, just like they taught you to do it by-hand in grade school. (Uhhh-h-h-h, back in my day, anyhow, when to use a pocket calculator was considered “cheating.”)
Perl does have a Math::Decimal package, which probably exposes the functionality that you might need here. (It says that it is “implemented mostly in XS,” but I have not taken the time to see whether it uses microprocessor decimal-math.) A package like this one will not be able to represent 1/3 exactly, simply because “base-10 can’t do that,” but it will be able to represent 1/10 exactly.
Incidentally, if this is a design consideration, you must also use DECIMAL types in your databases, and be certain that the entire soup-to-nuts handling of the numeric values does not ever stray into float-binary. (You must also confirm that the underlying representation used by the database system in question is, in fact, decimal.) Databases may also offer a CURRENCY type that, in most cases, is actually a scaled binary integer. (Internally, the number is multiplied by 10,000 to give four fixed digits to the right of the decimal point.) Once again, you must ensure that the entire data production-line never wanders into float-binary -land.
Perl does have the capability to represent a value internally as a true integer, although the bit-width of that integer may vary by implementation. Since it is a typeless language that tries its best to be accommodating, you must be mindful of exactly how Perl is representing and manipulating your values at all times ... if it matters. (As it certainly does, say when you are dealing with the final, double-underlined total at the bottom of a big, long invoice ...)
Replies are listed 'Best First'. | |
---|---|
Re^2: floating point addition
by syphilis (Archbishop) on Jan 12, 2015 at 23:35 UTC | |
by RonW (Parson) on Jan 13, 2015 at 00:15 UTC | |
by syphilis (Archbishop) on Jan 13, 2015 at 01:52 UTC |