ga*****@hotmail .com wrote On 09/07/06 13:53,:
Konstantin Miller wrote:
>>ga*****@hotma il.com wrote:
>>>I need to do just a few multiplies of long integers and have a
divide by ten. Can I avoid using floats? Can I use two longs
as a 64 bit value somehow? Thanks.
Hi!
Can you specify more clearly what you want to do? :-)
Konstantin
I have some long values in Liters and I want to convert to gallons (and
back). If I could do integer multiplication and divide by 10 I could
avoid the float library. Thanks.
Have you considered
long liters, gallons;
liters = ...whatever...;
gallons = liters * 3 / 10;
"Times three, over ten" is a crude approximation to 0.2641721,
but it's the only one I can think of that satisfies your desire
to divide by ten. If you're willing to consider other divisors,
more accurate conversions are possible:
gallons = liters * 26 / 100;
gallons = liters * 264 / 1000;
gallons = liters * 2642 / 10000;
...
You can convert from gallons back to liters the same way,
using various approximations to the conversion factor:
liters = gallons * 4;
liters = gallons * 38 / 10;
liters = gallons * 379 / 100;
...
However, all these conversions, no matter how accurate an
approximation you use, must eventually express the result as a
whole number of gallons or liters. You will need to chop or
round the "true" result to discard the fraction that a long
cannot express, and this introduces an unavoidable error: you
could be low by almost a gallon (if chopping, as shown) or either
high or low by as much as half a gallon (if rounding, not shown).
The error becomes especially nasty when you convert back
again, because the second conversion not only introduces its
own error (by discarding fractions of a liter), but also starts
from the slightly incorrect result of the first conversion. For
example, using the three-digit approximations above:
liters = 4;
gallons = liters * 264 / 1000;
liters = gallons * 339 / 100;
.... will yield liters==3 in the final step. There are at least
three ways to deal with this error:
- Switch to floating-point: There will still be errors, but
they will be much smaller. (For this kind of computation,
but not necessarily for all.)
- Switch to smaller units: Convert between milliliters and
teaspoons or some such. You'll still need to round or
chop, but the errors will be teaspoon-sized instead of
gallon-sized.
- Ignore it: Tell people the missing liter evaporated.
Your choice.
--
Er*********@sun .com