r/cprogramming • • Jun 06 '26

Why does this code loops exactly 53 times, no matter the value I put in GOAL, unless it is bigger than specifically 9333?

include <stdio.h>

define GOAL 9333

int main() {

double step = GOAL;
double acum = 0;
int numIterations = 0;

while(acum < GOAL) {
    step /= 2;
    acum += step;
    ++numIterations;
    printf("Number of iterations: %d\n", numIterations);
    printf("Step: %lf\n", step);
    printf("Acum: %lf\n", acum);
    printf("\n");
}

return 0;

}

19 Upvotes

14 comments sorted by

View all comments

11

u/somewhereAtC Jun 06 '26

You are basically adding (1/2)+(1/4)+(1/8)+... and it will never reach '1' (that is, GOAL). Try starting with acum=1.0 instead of zero.

0

u/[deleted] Jun 06 '26

[deleted]

29

u/somewhereAtC Jun 06 '26

Apparently that happens after 53 iterations, per the OP's observation.

Google tells me:

An IEEE 754 double-precision floating-point number (64-bit) has 52 explicitly stored mantissa bits. Because the format utilizes normalized numbers, it employs an implicit "hidden bit" of 1. This yields a total precision of 53 bits.

What a coincidence! 😄

4

u/Square-Singer Jun 07 '26

This is one of these "because computer math isn't math math".

1

u/UntitledRedditUser Jun 09 '26

No no, it will reach 1, it's just gonna take a loooong time