I am using Windows 7 with MinGW/GCC 4.7.1. I was trying to execute double ans = pow(2,1000) in C. I found that ans would not print correctly, no matter what I tried in terms of varying the data type.
However, I read (here, actually, at the very bottom of this page) that if the same thing were run on a Linux computer, it would print correctly.
I am aware of the limits imposed on char, int, and long long that are in the limits.h file in my MinGW folder, but where are the restrictions of double and float? Do/could these vary from one OS or architecture to the next?
EDIT:
Here’s the code, which prints out the truncated, zero-filled answer:
#include <stdio.h>
#include <math.h>
int main(void)
{
double ans = pow(2,1000);
printf("%.0f", ans);
return 0;
}
The question you’re asking isn’t related to the problem you’re seeing.
It’s very likely that all the systems you’re using us the same representation for type
double, namely 64-bit IEEE double-precision.The value of
pow(2, 1000)(or, more equivalently and more clearly,pow(2.0, 1000.0), is 2.01000. Since it’s a power of two, it can be represented exactly — but the relative precision of numbers that large is very coarse.A
doublevalue is typically precise to only about 15 or so decimal digits.Apparently the glibc implementation of
printf, used on Linux systems, attempts to print the full decimal representation of the value, while otherprintfimplementations replace some or all of the digits past the 15 or so significant digits with zeros. The latter is probably a bit easier to implement, but both approaches are valid.Running your program on several different systems, I get the following results (with lines folded for readability):
The last happens to be exactly equal to 21000.
The number you’re printing is unusual, in that it’s very large and exactly representable — and glibc goes to some extra effort to print it exactly. But more generally, floating-point values tend to be imprecise, and it’s seldom worth worrying about any digits past the first few.
For example,
pow(2.0, 1000.0) + 1.0cannot be represented exactly, and if you try to compute it, you’ll probably get exactly the same result aspow(2.0, 1000.0).