Toni Ivanov
Toni Ivanov

Reputation: 81

Replacing constant with variable of the same value and type, causes different results

int main()
{
    int nodes = 7;

    int var_1 = (int)(log((double)(nodes + 1))/log(2) - 1);
    int var_2 = (int)(log((double)(7 + 1))/log(2) - 1);

    printf("%d\n", var_1);
    printf("%d\n", var_2);

    return 0;
}

The above code initializes the varialbes var_1 and var_2 to values 1 and 2, accordingly.

Why they have different values since the variable nodes has the value of 7, same as the constant in the next equation.

Edit: I dont try to "fix" the code, or else I could just assign nodes+1 to a variable.

Upvotes: 0

Views: 142

Answers (1)

pmg
pmg

Reputation: 108988

The first statement is probably calculated at runtime by the code pre-compiled in the standard library (with libm), the second statement is probably calculated at compile time by the compiler (with MPFR).

Probably log(8) by libm is a tiny little bit less than by MPFR.

2.079441541...7 / 0.69314... = 2.999999...
2.079441541...8 / 0.69314... = 3.000000...

Upvotes: 1

Related Questions