Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing double variable contents

Tags:

c

double

printing

I tried following code snippet and output is surprising me:

#include <stdio.h>
#include <math.h>

int main()
{
            double num;
            unsigned char ch;

            ch = 19;
            num = 1.0E+20 ;
            num += ch * 1.0E+18;
            printf("E18 = %lf \n",num);
            printf("E18 = %e \n",num);

            num = 11.0E+21 ;
            num += ch * 1.0E+19;
            printf("E19 = %lf <------\n",num);
            printf("E19 = %e <------\n",num);

            num = 11.0E+22 ;
            num += ch * 1.0E+20;
            printf("E20 = %lf\n",num);
            printf("E20 = %e\n",num);

            num = 11.0E+23 ;
            num += ch * 1.0E+21;
            printf("E21 = %lf\n",num);
            printf("E21 = %e\n",num);

            num = 11.0E+24 ;
            num += ch * 1.0E+22;
            printf("E22 = %lf <------\n",num);
            printf("E22 = %e <------\n",num);
    return 0;
}

The output of the program:

E18 = 119000000000000000000.000000 
E18 = 1.190000e+20 
E19 = 11190000000000000524288.000000 <------
E19 = 1.119000e+22 <------
E20 = 111900000000000001048576.000000
E20 = 1.119000e+23
E21 = 1119000000000000044040192.000000
E21 = 1.119000e+24
E22 = 11189999999999999366660096.000000 <------
E22 = 1.119000e+25 <------

Why the data corrupted when printed while in exponent form its OK

like image 930
Adil Avatar asked Aug 19 '26 08:08

Adil


2 Answers

Because, you lose precision when the numbers grow big enough : http://en.wikipedia.org/wiki/Floating_point

like image 130
Tuomas Pelkonen Avatar answered Aug 22 '26 22:08

Tuomas Pelkonen


The data is not corrupted; that's simply how floating point values work in today's computers. Think of a float as a fixed number of digits (the mantissa) and another number that indicates where the decimal point should be placed (the exponent). For the long and more accurate story, Wikipedia is a good start.

Since the number of digits of the mantissa is fixed, it cannot represent the tiny fraction that you're asking for here. Furthermore, because it's all in binary, decimal numbers cannot always be represented exactly.

The exponential notation simply rounds off the last few digits where the number is known to be inaccurate, hence your results.

like image 20
Thomas Avatar answered Aug 22 '26 20:08

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!