Precision loss detection when converting from double to float

I am writing a piece of code in which I need to convert from double to float values. I am using boost :: numeric_cast to do this conversion, which will warn me of any overflow / stream. However, I am also interested to know if this conversion led to some kind of precision loss or not.

for example

double source = 1988.1012; float dest = numeric_cast<float>(source); 

Produces dest, which matters 1988.1

Is there any way in which I can detect this type of accuracy loss / rounding

+6
c ++ floating-point floating-accuracy rounding rounding-error
source share
4 answers

You can return the float to double and compare this double with the original - this should give you a fair indication of whether there was a loss of accuracy.

+11
source share
 float dest = numeric_cast<float>(source); double residual = source - numeric_cast<double>(dest); 

Therefore, residual contains the “loss” you are looking for.

+9
source share

Look at these articles for single precision and double precision floats. First of all, floats have 8 bits for the exponent versus 11 for the double. Thus, something larger than 10 ^ 127 or less than 10 ^ -126 in magnitude will be an overflow, as you mentioned. For a float, you have 23 bits for the actual digits of the number, versus 52 bits for a double. Obviously, you have a lot more precision digits for double than float.

Say you have a number: 1.1123. This number cannot actually be encoded as 1.1123, because the digits in the floating-point number are used to actually add as fractions. For example, if your bits in the mantissa were 11001, then the value will be formed 1 (implicit) + 1 * 1/2 + 1 * 1/4 + 0 * 1/8 + 0 * 1/16 + 1 * 1/32 + 0 * (64 + 128 + ...). The exact value cannot be encoded if you cannot add these fractions so that it is the exact number. This is rare. Therefore, there will almost always be a loss of accuracy.

+1
source share

You will have a certain level of loss accuracy, as Dave’s answer. If, however, you want to focus on quantifying and raising the exception when it exceeds a certain number, you will have to open a floating point number and analyze the mantissa and exponent, and then conduct an analysis to determine if ve exceeded your carry.

But the good news is usually the standard floating floating point IEEE .:-)

+1
source share

All Articles