I followed the solution here: How to Calculate Double + Float Precision and have been unable to calculate the maximum value for variables of type double.
I run:
double dbl_max = pow(2, pow(2, 10)) * (1-pow(2, -53));
printf("%.2e", dbl_max);
Result: inf
Or:
double dbl_max = (pow(2, pow(2, 10)));
printf("%.2e", dbl_max);
Result: inf
Or:
double dbl_max = pow(2, pow(2, 9)) * (1-pow(2, -53));
printf("%.2e", dbl_max);
Result: 1.34e+154
Why isn't the calculation fitting into the variable? The top sample above works just fine for float variables.
pow(2, 10)
to(pow(2, 10) - 1)
and it should work. You can compensate by multiplying the final result by 2.pow
to calculate powers of 2. A good math library will get these right, but not all math libraries will—pow
is a floating-point function, and math libraries of mediocre quality will return approximate results. To produce an integer power of two in floating-point, useldexp(1, n)
fordouble
orldexpf(1, n)
forfloat
, wheren
is an integer. To produce a power of two in integer, use(type) 1 << n
, where “type” is the integer type you want for the result, such asuint32_t
.