Re: [SLUG] {SPAM?} High Precision Floating Point Numbers

From: Backward Thinker (backwardthinker@juno.com)
Date: Fri Mar 19 2004 - 08:02:05 EST


> Anyone have tips on how to ensure high precision in mathematical
> operations dealing with floats and doubles in C? These numbers will
> typically be dollars, and I don't want a lot of imprecise results
> when doing math on them. (Because floats and doubles represent
> decimal numbers as binary, they're very prone to loss of precision.)

Typically be dollars, or always be dollars? One tip to ensure high precision with doubles is to not use doubles :). Really, if you are always going to be dealing with a known level of decimal places (like 100ths), skip the binary fraction representation woes of having to figure out if you have enough bits of precision for the range of values YOU anticipate, and just use ints (long long or whatever). You can deal with everything internally as units of 100ths (so 1 dollar is 100 cents), and only worry about representing the decimal point yourself when you need to write it to output. The case where you have to be careful is when multiplying/dividing your 100ths by a non-integer, like an interest rate. Then you must adjust your units back to 100ths since that operation may have "moved" the decimal place, and you might have to end up rounding with "eighth-unit" rates like 4.125% or "gas-price" rates like 4.495%. But if you need to worry about this and rounding, you could al!
ways do your math in units of 1000ths, or 10000ths, or whatever precision you really need.

Before you throw this method out as completely stupid, realize that one of its plusses is accuracy (no binary fractions!), AND it's very easy to test for overflow if your program starts dealing with input values larger than you, the programmer, anticipated when you selected your datatype. With doubles (don't use floats), you just start losing precision "without warning" and those rounding errors can be expensive ;).

If you want to still need to stick with real-type numbers, http://www.nuvisionmiami.com/books/asm/workbook/floating_tut.htm has lots of examples to understand how things are represented behind the scenes.

HTH, not sure I way I came off as such a salesman :).
~ Daniel

________________________________________________________________
The best thing to hit the Internet in years - Juno SpeedBand!
Surf the Web up to FIVE TIMES FASTER!
Only $14.95/ month - visit www.juno.com to sign up today!
-----------------------------------------------------------------------
This list is provided as an unmoderated internet service by Networked
Knowledge Systems (NKS). Views and opinions expressed in messages
posted are those of the author and do not necessarily reflect the
official policy or position of NKS or any of its employees.



This archive was generated by hypermail 2.1.3 : Fri Aug 01 2014 - 19:25:51 EDT