Search code examples
cdouble

why new numbers appear at the end of double variable?


Here is my code:

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

double Mul(double X,double Y,double Z)
{
    Y=Y*pow(10,6);
    Y=Y+Z;
    X=(X*pow(10,12))+Y;
    //X=114360000000000000+117239051145;
    //X=Y;
    
    return X;
}

int main()
{
    double Hello=Mul(114360,117239,511432);
    printf("%f",Hello);

    return 0;
}

The output should be "114360117239511432" but I got "114360117239511424" I need to know why 511432 converts to 511424? and How can I solve this problem?


Solution

  • I suggest to get familiar with floating point inaccuracy. However you use decimal numbers as parameters, they are not integers. If you want to know more of the integer limits, please check the numeric limits.

    Let me be more specific. Double type become inaccurate if the exponent other than 1. I modified a bit your code, to show what are the exact values.

    double Mul(double X, double Y, double Z)
    {
        double YbutMore = Y * pow(10, 6);
        // YbutMore = 117239000000.00000
    
        double YandZ = YbutMore + Z;
        // YandZ = 117239511432.00000
    
        double Xpow12 = X * pow(10, 12);
        // Xpow12 = 1.1436000000000000e+17
    
        return Xpow12 + Y;
        // returns 1.1436000000011723e+17
    }
    

    So it all begins when we do a X * pow(10, 12). The mantissa cannot hold this big number, so the exponent will be other than 1 that will cause the inaccuracy. Don't forget to check the double value memory model.

    If you are intrested how to store accurate and large numbers, please see How to store extremely large numbers?