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.
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.
