Re: I don't get how the computer arrives at 2^31



Chuck F. wrote:
> Chad wrote:
> >
> > Okay, maybe I'm going a bit off topic here, but, I think I'm
> > missing it. When I go something like:
> >
> > include <stdio.h>
> > #include <math.h>
> >
> > int main(void) {
> > int i = 0;
> > double sum = 0;
>
> Why initialize these, when the initial values will never be used?

The initial value of 'i' isn't used, but the initial value of 'sum'
certainly is.

I personally wouldn't intialize 'i', but some people argue that doing
so is a safety measure. In my personal experience, this "safety"
measure frequently prevents the symptoms of incorrectly written code
from being serious enough to be noticed, which in my opinion is a bad
thing. If my code uses the value of an object before that object has
been given the value it was supposed to have at that point, I'd greatly
prefer it if the value it uses is one that's likely to make my program
fail in an easily noticeable way. 0 is often not such a value. An
indeterminate one is more likely to produce noticeable symptoms. A
well-chosen specific initializer could be even better, except for the
fact that it gives the incorrect impression that the initializing value
was intended to be used. This can be fixed by adding in a comment:

int i = INT_MAX; // intended to gurantee problems if the program
incorrectly uses this value

But I prefer the simplicity of:

int i;

> > for (i = 0; i <= 30; i++) {
> > sum = pow(2.0, i) + sum;
> > }
> > printf("The value of c is: %0.0f\n",sum);
> > return 0;
> > }
> >
> > The output is:
> > $./pw
> > The value of c is: 2147483647 (not 2147483648).
> >
> > The way I understood this was that for 32 bits, pow(2.0, 31.0)
> > would look something like the following:
> >
> > 1111 1111 1111 1111 1111 1111 1111 1111
> >
> > The first bit would be signed. This means that the value should
> > be the sum of:
> > 1*2^0 + 1*2^1..... 1*3^30
> >
> > Why is the value off by one?
>
> Because a double is not an integral object. It expresses an
> approximation to a value, and the printf format has truncated the
> value. Just change the format to "%f\n" to see the difference.

Did you try that? I think you'll be surprised by the results. Just to
make things clearer, you might try using long double, and a LOT of
extra digits after the decimal point. If you've got a fully conforming
C99 implementation, it would be even clearer if you write it out in
hexadecimal floating point format.
Hint: it's not the program that's giving the wrong value for the sum of
this series.

.



Relevant Pages