0

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?

John Jin
  • 131
  • 5

1 Answers1

1

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?

zerocukor287
  • 555
  • 2
  • 8
  • 23
  • I appreciate your comment. I've changed the datatype to uint64_t( instead of double) and the accuracy is the same as the last code. Is there any way to compensate the effect of X * pow(10, 12)? – John Jin Nov 24 '21 at 03:48
  • 2
    @JohnJin, `pow` works by using doubles, even when giving it integer arguments. What you need is a power function that does its calculation using `uint64_t`. There should be a lot of implementations out there if you are willing to search the net. – HAL9000 Nov 24 '21 at 15:29