1

I just have a few lines of code C++ bellow:

    long re = 103491683;
    double temp = (double)re * (double)re;
    cout<<"\n"<<"double * double = \t"<<(long)temp;
    long temp2 = re * re;
    cout<<"\n"<<"long * long = \t\t"<<temp2;

and it returns 2 different value:

    double * double =   10710528450172488
    long * long =       10710528450172489 

I cannot understand what happen, I had this bug on java and I also tried on C++ and that's problem. Please help me (sorry for my poor English)

Notinlist
  • 16,144
  • 10
  • 57
  • 99
duongtd23
  • 101
  • 1
  • 6
  • 2
    Where is the *parsing*? – Biffen Mar 30 '16 at 07:46
  • http://stackoverflow.com/questions/14265785/why-does-multiplying-two-large-double-numbers-give-a-wrong-result – Mourad Mar 30 '16 at 08:03
  • [Representing integers in doubles](http://stackoverflow.com/q/759201/995714), [Loss of precision - int -> float or double](http://stackoverflow.com/q/2781086/995714) – phuclv Mar 30 '16 at 08:06

3 Answers3

1

A double number has 64 bits storage. Of those 64, 1 is used to store the sign, 11 are stored for the exponent and 53 are stored for decimal digits. This means that the maximum precision in your number you can reach is 15.95 decimal digits 53 * log10(2).

Your number 10,710,528,450,172,489 has 17 decimal digits and thus slightly goes beyond the precision that can be reached in a double.

The maximum number that can be reached in a signed long on 64-bits systems is 2^63 - 1 = 9,223,372,036,854,775,807 which is larger than the number you have.

Chiel
  • 6,006
  • 2
  • 32
  • 57
0

The double type has precision of 52 binary bits, other bits are to store exponent and one to store the sign. The long type (on most 64 bit systems) has 63 bits precision and one to store the sign. In the double * double calculation you have lost your least significant bit.

See https://en.wikipedia.org/wiki/IEEE_floating_point

More precisely for this example: https://en.wikipedia.org/wiki/Double-precision_floating-point_format

Notinlist
  • 16,144
  • 10
  • 57
  • 99
0

Doubles have a certain amount of imprecision because of how the number is stored internally. When you do math operations with doubles, this imprecision can be compounded. If your code needs to be able to deal with decimal places and this is an unacceptable amount of error, consider using a library which allows larger decimal numbers. If all possible values of re are always going to be integers, then the long version should work fine.

suddjian
  • 1,986
  • 2
  • 16
  • 25