Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting precision loss when converting from double to float

I am writing a piece of code in which i have to convert from double to float values. I am using boost::numeric_cast to do this conversion which will alert me of any overflow/underflow. However i am also interested in knowing if that conversion resulted in some precision loss or not.

For example

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

Produces dest which has value 1988.1

Is there any way available in which i can detect this kind of precision loss/rounding

like image 459
Yogesh Arora Avatar asked Jul 13 '10 17:07

Yogesh Arora


People also ask

Does double have more precision than float?

double has 2x more precision than float. float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision.

Why do floating point numbers lose precision?

Floating-point decimal values generally do not have an exact binary representation. This is a side effect of how the CPU represents floating point data. For this reason, you may experience some loss of precision, and some floating-point operations may produce unexpected results.

Can double be converted to float?

Here double is a primitive data type its object can't be used to call the Float class method.

How accurate is double float?

Double precision numbers are accurate up to sixteen decimal places but after calculations have been done there may be some rounding errors to account for. In theory this should affect no more than the last significant digit but in practice it is safer to rely upon fewer decimal places.


2 Answers

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

Hence, residual contains the "loss" you're looking for.

like image 154
Jacob Avatar answered Oct 13 '22 01:10

Jacob


You could cast the float back to a double and compare this double to the original - that should give you a fair indication as to whether there was a loss of precision.

like image 20
Will A Avatar answered Oct 12 '22 23:10

Will A