On Fri, Mar 19, 2004 at 01:02:05PM +0000, Backward Thinker wrote:
>
> > 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 :).
Your solution was actually my first choice. I wrote a set of money
routines a while back that do essentially what you're talking about.
Like:
typedef struct {
int dlr;
int cnt;
} money;
I was just wondering if there was a simpler way to do it without going
that route. Just curious, though, why not use floats?
Paul
-----------------------------------------------------------------------
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:28:01 EDT