In the following code why do the sum and cast_sum results diverge at 2^53? The results of pow(2, 53)
and (uint64_6) pow(2, 53)
appear the same but when I sum them I get different results. Overall goal was to sum the results of 2^0 through 2^63. I just don't understand why using pow(2, i)
fails and (uint64_t) pow(2, i)
works. Or why the results of the two differ starting at 2^53.
#include <math.h>
#include <stdio.h>
int main() {
uint64_t sum = 0;
uint64_t cast_sum = 0;
for (int i = 0; i < 65; ++i) {
sum += pow(2,i);
cast_sum += (uint64_t) pow(2,i);
printf("i: %d, 2^%d = %lf, sum: %lu, cast_sum:%lu\n", i, i, pow(2, i), sum, cast_sum);
}
}
i: 52, 2^52 = 4503599627370496.000000, cast of 2^52: 4503599627370496, sum: 9007199254740991, cast_sum:9007199254740991
i: 53, 2^53 = 9007199254740992.000000, cast of 2^53: 9007199254740992, sum: 18014398509481984, cast_sum:18014398509481983
i: 54, 2^54 = 18014398509481984.000000, cast of 2^54: 18014398509481984, sum: 36028797018963968, cast_sum:36028797018963967```