0

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.

2
  • The intermediate exponent is one too high. Change pow(2, 10) to (pow(2, 10) - 1) and it should work. You can compensate by multiplying the final result by 2.
    – Tom Karzes
    Commented Nov 14, 2017 at 5:08
  • Do not use 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, use ldexp(1, n) for double or ldexpf(1, n) for float, where n 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 as uint32_t. Commented Nov 14, 2017 at 14:59

1 Answer 1

1

The intermediate exponent is one too high. Change pow(2, 10) to (pow(2, 10) - 1) and it should work. You can compensate by multiplying the final result by 2. – Tom Karzes

double dbl_max = pow(2, pow(2, 10)-1) * (1-pow(2, -53)) * 2;
printf("%.2e", dbl_max);
1
  • Thank you Elad. Why is the intermediate exponent too high? I would think the calculation should fit exactly into the variable. Is it related to what Eric said about inferior math libraries returning approximate results? Commented Nov 17, 2017 at 1:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.