Frank said:
Hello group
I am looking for a function written in standard C witch can perform the a
* b / c on a long int without loosing any bits. a * b can exceed 32 bits
and if I carst a,b and c to floats I will still loos precision on the last
bits.
My compiler only supports 4 byte long int and 4 byte float
hope someone can help me
If your compiler supports `long long', that'd be
the easiest to implement and would give "perfect" results.
Failing that, does your compiler provide a `double'
that's significantly more precise than `float'? On most
machines `double' isn't large enough to handle `int * int'
with perfect accuracy, but you could get awfully close
with (pseudocode; little matters like signs ignored):
double r = (double)max(a, b) / c;
return (int)(r * min(a, b));
Failing even that, look for a "big number" package;
see the FAQ for some suggestions. Most such packages
are overkill in the sense that they provide "unlimited"
precision whereas you need only double precision, but
some may have double-precision specializations -- or you
could just go ahead and accept the overhead.
And, of course, there's the "roll your own" method.
A lot depends on what the calculation is being used
for. If you're doing something like data compression or
cryptography, say, you need a solution that gives perfect
accuracy in every bit. If you're rescaling an image that's
going to go through anti-aliasing anyhow, you can afford
a little bit of wiggle in the low-order bits; the "double
as ratio" approach might be good enough.