Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Program giving inaccurate value

The below program calculates 262 + 261 + 260 + … + 21 + 20.

Using double type to store sum:

double sum = 0;
  for (int i = 0; i < 63; i++) {
    sum += pow(2.0, i);
    // print("i : $i sum : $sum");
  }
  print(sum);

OUTPUT:

9223372036854776000.0

It is clear that answer should be an odd number but the sum is : 9223372036854776000.0 which is an even number.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I change the sum to int data type it’s giving the accurate result:

Using int type to store sum:

int sum = 0;
for (int i = 0; i < 63; i++) {
  sum += pow(2.0, i).toInt();
  //print("i : $i sum : $sum");
}
print(sum);

OUTPUT:

9223372036854775807

When the datatype is double why the summation is generating wrong result ?

>Solution :

Because a double only has 52 significant bits in the mantissa, whereas your number has 63.

1 sign bit, 11 exponent bits, and 52 mantissa bits

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading