Re: conversion problem int <-> double ?
On Mar 31, 7:04 pm, Markus Dehmann <markus.dehm...@gmail.com> wrote:
I have two integers i1 and i2, the second of which is guaranteed to be
between 0 and 99, and I encode them into one double:
double encoded = (double)i1 + (double)i2 / (double)100;
So, for example, 324 and 2 become 324.02. Now I want to decode them
using the function given below but it decodes the example as 324 and
1, instead of 324 and 2.
The problem is that floating point values usually have a binary
representation. So precise decimal values (such as 324.02) often
cannot be exactly represented with a floating point type. Instead, the
floating point type stores the representable value nearest to the
value specified (for example, the nearest representable value to
324.02 is likely 324.01999).
One solution would be to use decimal floating point arithmetic.
Decimal floating point arithmetic would be able to represent 324.02
exactly. But although support for decimal floating arithmetic is
likely coming to the C++ library, actual implementations of this
feature are not that common.
A more likely (and practical) solution might be to use "fixed-point"
arithmetic. Fixed point arithmetic is completely accurate - up to the
specified resolution. For example, performing the above calculation
with fixed point arithmetic (with 1/100 resolution) might look
something like this:
typedef long Fixed; // in 1/100ths of a unit
Fixed n = 32402;
long p = n/100;
long i = n%100;
Greg